If there is novice learning Nodejs Get URL post When the parameters are returned, the same problem will happen to me, and today we will solve this problem.

Node.js Unlike PHP This old backend language has a specific way to obtain external parameters, after all, it is a new force, hoping that the later version will be more convenient and efficient.


 / / normal acquisition value 
app.get ("/", (req, RES) = {
console.log (req.query); 
res.send ("finish");}; 
app.post ("/", (req, RES) = > {
console.log (req.body); 
res.send ("finish");};

If you want to export normally, your anticipation is like this.

 / / GET request 
{
name: 'Feng Xiaoxian', 
age:'18'
}
 complete.

or

 / / POST request 
{
name: 'Feng Xiaoxian', 
age:'18'
}
 complete.

However, it is not!!!

 / / the two output will be like this!!! {}
undefined

This is because we lack a module, express middleware. Body-parser

Official statement
Node.js body parsing middleware.
Parse incoming request bodies in a middleware before your handlers, available, handlers

Basically, parsing the content of the body in the client request, JSON encoding and URL encoding processing.


Next we will install. Body-parser

 / / install body-parser
npm install body-parser

 / / import app.js
var bodyParser = require ('body-parser'); 
app.use (bodyParser); / so / req.body, to use req.body to get the value of post transfer, 
app.post ("/", (req, RES) = > 
app.post ("));" ("completion");};

Label: Nodejs , Post , Express

Add new comments