req.body返回undefined并安装了body-parser包

时间:2018-06-14 23:58:16

标签: node.js express post

我正在尝试在express中运行post方法但是我遇到了一个问题,试图在req.body中获取post参数。我已经在我的app.js文件中安装了body-parser包。

var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

我已尝试将扩展设置为true和false的代码。当我运行这段代码时,我得到了返回{}。

app.post("/postfunction", function(req, res) {
    console.log(req.body)
});

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个

var express = require('express'),
app = express(),
bodyParser = require('body-parser');

app.use(bodyParser.json());

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


app.post('/form',function(req, res){
res.setHeader('Content-Type', 'application/json');

    setTimeout(function(){

        res.send(JSON.stringify({
        firstName: req.body.firstName || null,
        lastName: req.body.lastName || null
        }));

    }, 1000)

  console.log('you posted: First Name: ' + req.body.firstName + ', Last Name: ' + 
    req.body.lastName);
  });

app.listen(3000, function () {
    console.log('Server is running. Point your browser to: http://localhost:3000');
 });