Having an issue with accessing data from req.body in my form created with JS
{ 'object Object': '' }
//when using JSON.stringify:
{ '{"A":"a","B":"b","C":"c"}': '' }
Client
var body = `{
"A": "a",
"B": "B",
"C": "c"
}`
body = JSON.parse(body) // Object { A: "a", B: "b", C: "C" }
body = JSON.stringify(body) // "{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"}"
const opts = {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
},
body
}
console.log(body)
fetch(`${document.URL}/post`, opts).then((response) => {
console.log(response.status);
console.log(response.json());
})
})
server
router.post("/post", auth, async (req, res) => {
console.log(req.body)
res.status(201)
res.end()
});
Seeking help on converting this format
{ '{"A":"a","B":"b","C": "c"}': '' }
to desired format:
{ A: "a", B:"b", C: "c"}
Solution
Special shoutout to Barmar and Phil for providing the solution.
Simply replace
"content-type": "application/x-www-form-urlencoded"
with "Content-type": "application/json",
in the headers.
Additionally, add app.use(express.json())
in server.js file.