【问题标题】:req.body returning undefined with body-parser packages installedreq.body 返回 undefined 并安装了 body-parser 包
【发布时间】:2018-06-14 23:58:16
【问题描述】:

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

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)
});

有什么想法吗?

【问题讨论】:

  • 向我们展示你的 html,它将把这个 post 请求发送到服务器
  • 这是我试图发送的请求:localhost:3000/postfunction?key1=test1&key2=test2.
  • 我无法访问您的本地主机 o.O 。你应该使用req.query 而不是req.body
  • POST 数据由带有 name 属性的表单输入字段提交,GET 数据由查询字符串传递。

标签: node.js express post


【解决方案1】:

试试这个

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');
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2021-08-08
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多