Express.js req.body undefined

前端 未结 30 2496
半阙折子戏
半阙折子戏 2020-11-22 12:02

I have this as configuration of my Express server

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: \"keyboard cat\" }         


        
相关标签:
30条回答
  • 2020-11-22 12:43

    No. You need to use app.use(express.bodyParser()) before app.use(app.router). In fact, app.use(app.router) should be the last thing you call.

    0 讨论(0)
  • 2020-11-22 12:43

    I solved it with:

    app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
    });
    
    0 讨论(0)
  • 2020-11-22 12:43

    If you are using some external tool to make the request, make sure to add the header:

    Content-Type: application/json

    0 讨论(0)
  • 2020-11-22 12:44

    Looks like the body-parser is no longer shipped with express. We may have to install it separately.

    var express    = require('express')
    var bodyParser = require('body-parser')
    var app = express()
    
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
    
    // parse application/json
    app.use(bodyParser.json())
    
    // parse application/vnd.api+json as json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
    app.use(function (req, res, next) {
    console.log(req.body) // populated!
    

    Refer to the git page https://github.com/expressjs/body-parser for more info and examples.

    0 讨论(0)
  • 2020-11-22 12:44

    Use app.use(bodyparser.json()); before routing. // . app.use("/api", routes);

    0 讨论(0)
  • 2020-11-22 12:44

    You can try adding this line of code at the top, (after your require statements):

    app.use(bodyParser.urlencoded({extended: true}));
    

    As for the reasons as to why it works, check out the docs: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions

    0 讨论(0)
提交回复
热议问题