📅  最后修改于: 2023-12-03 15:14:57.251000             🧑  作者: Mango
If you are receiving the error message "express post body undefined" while working with Node.js and the Express framework, it means that there is an issue with the way you are handling the request body.
When you make a POST request to the server, the data is sent in the request body. By default, Express does not parse the request body, so you need to use a middleware function like body-parser to parse it.
To resolve the "express post body undefined" error, follow these steps:
If you have not already installed the body-parser package, you can do so using npm:
npm install body-parser --save
Next, require the body-parser package at the top of your Node.js file:
var bodyParser = require('body-parser');
Use the body-parser middleware function to parse the request body and store it in a variable:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Now, you can access the request body using the req.body
property in your route handler:
app.post('/example', function(req, res) {
var data = req.body;
// Do something with the data
res.send('Data received');
});
The "express post body undefined" error occurs when the request body is not properly parsed by a middleware function. By using the body-parser middleware and accessing the request body using the req.body
property, you can resolve this error and properly handle POST requests in your Node.js application.