Express.js req.body undefined

前端 未结 30 2518
半阙折子戏
半阙折子戏 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:29

    UPDATE July 2020

    express.bodyParser() is no longer bundled as part of express. You need to install it separately before loading:

    npm i body-parser
    
    // then in your app
    var express = require('express')
    var bodyParser = require('body-parser')
     
    var app = express()
     
    // create application/json parser
    var jsonParser = bodyParser.json()
     
    // create application/x-www-form-urlencoded parser
    var urlencodedParser = bodyParser.urlencoded({ extended: false })
     
    // POST /login gets urlencoded bodies
    app.post('/login', urlencodedParser, function (req, res) {
      res.send('welcome, ' + req.body.username)
    })
     
    // POST /api/users gets JSON bodies
    app.post('/api/users', jsonParser, function (req, res) {
      // create user in req.body
    })
    

    See here for further info

    original follows

    You must make sure that you define all configurations BEFORE defining routes. If you do so, you can continue to use express.bodyParser().

    An example is as follows:

    var express = require('express'),
        app     = express(),
        port    = parseInt(process.env.PORT, 10) || 8080;
    
    app.configure(function(){
      app.use(express.bodyParser());
      app.use(app.router);
    });
    
    app.listen(port);
        
    app.post("/someRoute", function(req, res) {
      console.log(req.body);
      res.send({ status: 'SUCCESS' });
    });
    

提交回复
热议问题