Express js req.body returns empty

后端 未结 2 1633
南笙
南笙 2021-01-18 23:57

I\'ve tried the all solutions from some another stackoverflow posts but it didn\'t solved my issue.

Here is my app.js

var express = requ         


        
2条回答
  •  太阳男子
    2021-01-19 00:06

    body-parser

    The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body, or an empty object {} if there was no body to parse (or an error was returned).


    app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
    

    A new body object containing the parsed data is populated on the request object after the middleware, req.body will contain the parsed data, this object will contain key-value pairs, where the value can be a string or array

    The Content-Type is application/x-www-form-urlencoded


    app.use(bodyParser.json()); // for json encoded bodies
    

    A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).

    The Content-Type is application/json


    application/json is used when you are posting the data {"test":"hello"} like this. www-form-url-encoded is used to get the data as key-value in object from the url when used the app.use(bodyParser.urlencoded({ extended: true }));. They both are different and have their own use cases

提交回复
热议问题