I am trying to do a simple post from Reactjs to a node.js server using node-fetch; however, the body of my request is always empty (I have not been able to come up with any configuration which results in a non-empty body). I have read seemingly every stackOverflow question about this and none solves my predicament, sadly. Here is my reactjs code:
fetch('http://localhost:3000/sayhello/', {headers: new Headers({
'Content-Type': 'application/json'
}), method: 'POST', body: {"nose":"bop"} })
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
And my server.js: ... import BodyParser from 'body-parser';
app.use(BodyParser.urlencoded({extended : true}));
app.use(BodyParser.json());
app.post('/sayhello/', function(req, res) {
console.log(req.body);
res.send(req.body);
});
The console always gives an empty body, and the response is always undefined. This happens too when rather than JSON I just post a string as body. Any ideas?
Thanks
Not to worry friends it seems I have figured it out. I was missing JSON.stringify in body. I hope this helps someone sometime, so they avoid pulling out as much hair as I did :)