Hey i use a react app for call a express app:
fetch('/api/sendmail', {method: 'POST', body: JSON.stringify(payload) })
Payload =
const payload = {
fsdfdsdfsdfsdsfa: 1,
b: 2
};
On express app i try to get body content:
app.post("/api/sendmail", (req, res) => {
console.log(req.body)
res.json({ message: 'aa' });
});
but console.log(req.body) return undefined
How i can resolve that.
I'd assume you simply missing something like this in your init file:
app.use(bodyparser.json())
Also try adding Content-Type: application/json as your request header
I think for express to be able to parse POST requests you need a body-parser middleware.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
})
You will have to install "body-parser" though. I heard express comes with it's own body-parser now but I have no info on that so you will have to read the docs