I am submitting form data on the root route /
using the POST method. The form data is used by the server to fetch some data from other APIs. However, in the response , I am always receiving a text/html
data and not json
response.
Form handler
function handleSubmit(event) {
event.preventDefault()
showSpinner()
const tripName = document.getElementById('tripName')
const tripDest = document.getElementById('tripDestination')
const startDate = document.getElementById('fromDate')
const endDate = document.getElementById('toDate')
tripDetails.tripName = tripName.value
tripDetails.tripDest = tripDest.value
tripDetails.startDate = startDate.value
tripDetails.endDate = endDate.value
fetch('/',{
method : 'POST',
headers : {
"Content-Type" : "application/json"
},
body : JSON.stringify({tripDetails : tripDetails})
}).then((res) => {
console.log(res.headers.get('Content-Type'));
res.text().then((data) => {
return data;
});
})
}
Response on client
However, when I open Postman to test my server side , I get the desired json response from the APIs.
Server side code
app.post('/', (req, res) => {
console.log(req.body);
fetch(`http://api.geonames.org/searchJSON?name=${req.body.tripDest}&username=${GEONAMES_API}`)
.then(data => data.json())
.then(data => {
destCoords.latitude = data.geonames[0].lat
destCoords.longitude = data.geonames[0].lng
return fetch(`https://api.darksky.net/forecast/${DARK_SKY_API}/${destCoords.latitude},${destCoords.longitude}`)
})
.then(data => data.json())
.catch(err => `Error >>> ${err}`)
.then(data => {console.log(data);res.send(data)})
.catch(err => `Error in sending data to client >>> ${err}`)
})
Server side output
What exactly is happening here? I am unable to understand how the client is unable to receive the server json data .
Also, I am using webpack to build my application . Am not sure if that could cause any issues since its the first time I am using it. The dist
folder is created correctly and the app compiles successfully too.