I am trying to post form data from react to node backend, How to do thtat ? my React code is :
import fetch from 'isomorphic-fetch';
export function createBio (data) {
console.log(data);
return fetch('http://localhost:3001/user/create', {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
}
}).then(res => {
return res;
}).catch(err => console.log(err));
}
My NodeJs code
router.post('/create', (req,res,) => {
var user = new User({title: req.params.title || "Untitled Note", body: req.params.body});
user.save();
});
How to retrieve data
You can use body-parser middleware to parse the body of your request
in your server.js:
and supposing you send an object to the server like:
You can then get it in the request:
This will log:
I would also strongly recommend using Axios for your requests instead of fetch, and read my answer in this post where I discuss some differences and how to implement axios if you are using fetch already. This way you don't need to stringify your data for example, and you solve other issues discussed there.
If you use Axios (with async/await), set your request object like so:
And send the request to axios with: