I send data with fetch()
in HTML to an express API, this is how it comes out in the req.body
(I use body-parser)
{
'{"address":"a","town":"NYC","details":"a","appr":': { '"Car1"': '' }
}
it's all "stringy", as the only way I know to "parse it" to send it, is to send it with JSON.stringify. But, upon getting the info, it's "unparseable", JSON.parse errors with "unexpected string in JSON at position 62"
I send it like:
body: JSON.stringify({
address: address,
town: town,
details: details,
appr: apr,
}),
I've tried everything I know how to do to attempt to "make it a JSON" again, but nothing has worked.
CodePudding user response:
1 - Don't forget to add header to fetch
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json' // => this is important
},
body: JSON.stringify(data)
});
2 - Don't forget to add this on express
app.use(bodyParser.json())
Note: If you are using Express v4.16.0 or newer you can use built-in middleware. Thanks to @Dov Rine
app.use(express.json());
3 - req.body will be available as object after this. You should not use JSON.parse(req.body) because body-parser does this for you.
let address = req.body.address;