Im fetching my current location in client side and I'm using fetch.
if ('geolocation' in navigator) {
console.log('geolocation available');
navigator.geolocation.getCurrentPosition(async (position) => {
console.log(position.coords.latitude, position.coords.longitude);
let lat = position.coords.latitude;
let lng = position.coords.longitude;
document.getElementById('latitude').textContent = lat;
document.getElementById('longitude').textContent = lng;
const data = { lat, lng }
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify(data)
};
console.log(options, "options")
let response = await fetch('/api', options)
const datas = await response.json();
console.log(datas, 'after fetch');
});
} else {
console.log('geolocation not available')
}
At the server side I'm doing post
const express = require("express");
const app = express();
app.use(express.static('public'));
app.use(express.json({ limit: '1mb' }));
// app.use(express.urlencoded());
app.listen(3000, () => console.log('listening at 3000'))
app.post('/api', (request, response) => {
console.log('I got a request');
console.log(request.body,"req");
response.json({
status: 'success',
latitude: request.body.lng,
longitude: request.body.lat
})
})
But I'm not getting the data in the request body
listening at 3000
I got a request
{} req
Please help me solve this as its been long I'm failing to debug it.
CodePudding user response:
Your console loging body so you should send body
const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) };
CodePudding user response:
You probably need body-parser to handle json body
https://www.npmjs.com/package/body-parser
var express = require('express')
var bodyParser = require('body-parser');
var app = express()
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());