In express.js, an HTTP web server library for the node.js language, you may encounter a TypeError: Cannot read property xx of undefined error when trying to retrieve POST data (body).
When sending an HTTP POST request with a request body to express.js, you get a TypeError: Cannot read property xx of undefined error.
curl http://192.168.0.110:8111/config -X POST -d 'content=hogehogehoge'
First, install the package:
npm install --save body-parser
Add the following code:
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
Now you can retrieve HTTP POST data with req.body.value.
Below, as per the curl command above, we use req.body.content to retrieve content.
app.post('/config', async (req, res, next) => {
try {
console.log(req.body.content) ;
res.send("something here.")
next();
} catch (error) {
next(error);
}
});
The method may vary depending on the version of express.js.
javascript - How to retrieve POST query parameters? - Stack Overflow