【问题标题】:Express.js POST req.body emptyExpress.js POST req.body 为空
【发布时间】:2016-07-10 17:41:07
【问题描述】:

所以我在使用 node.js 运行的 server.js 文件中有以下代码。我正在使用 express 来处理 HTTP 请求。

app.post('/api/destinations', function (req, res) {
  var new_destination = req.body;
  console.log(req.body);
  console.log(req.headers);
  db.Destination.create(new_destination, function(err, destination){
    if (err){
      res.send("Error: "+err);
    }
    res.json(destination);
  });
});

我在终端中运行以下命令:

curl -XPOST -H "Content-Type: application/json" -d '{"location": "New York","haveBeen": true,"rating": 4}' http://localhost:3000/api/destinations

运行 server.js 后会打印出以下内容。

{}
{ host: 'localhost:3000',
  'user-agent': 'curl/7.43.0',
  accept: '*/*',
  'content-type': 'application/json',
  'content-length': '53' }

所以 req.body 是 {}。我阅读了其他有关由于正文解析器而导致内容类型不正确的类似问题的 Stack Overflow 帖子。但这不是问题,因为 content-type 是 application/json。

任何想法如何获取请求的实际正文?

提前致谢。

【问题讨论】:

  • 你确实使用 body-parser 中间件,对吧?
  • 如果你是:如何,究竟是什么?
  • 我正在使用正文解析器。基本上只需要它然后“app.use(bodyParser.urlencoded({extended: true }));”当然没有引号。
  • urlencoded()not 处理 application/json (hint)。
  • 非常感谢@robertklep 添加 bodyParser.json() 修复它。不敢相信我忘记了....非常感谢

标签: javascript json node.js express body-parser


【解决方案1】:

你还需要 bodyParser.json:

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

【讨论】:

  • 这行得通。非常感谢!!不敢相信我忘记了。
  • 谢谢!不知道为什么,但是当我在阅读您的评论后尝试app.use(bodyParser.json()); 时,它起作用了,尽管我之前尝试过很多次。一定是个神奇的答案;)
  • 尽管包含了两条线,但我的身体仍然是空的。不知道为什么。
  • 我已经完成了你们在这里建议的一切,但没有任何效果。我想知道为什么会发生这个错误?请给出好的答案!
  • 你告诉我一个 f(*@@( 网络框架不允许我访问通过 POST 传入的数据,除非我扩展它?!
【解决方案2】:

如果您忘记将 name 属性放入表单输入字段,req.body 有时会显示 {}。下面是一个例子:

<input type="email" name="myemail" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>

然后req.body显示{ myemail: 'mathewjohnxxxx@gmail.com' }

我发布这个答案是因为,我遇到了类似的问题,这对我有用。

【讨论】:

  • 我想知道为什么正文解析器只适用于输入中的“名称”属性,而不仅仅是“id”。这个答案对我帮助很大,有时我们只是忘记了这些基本的东西。 Ps:在 .NET 中,我从未在输入字段中使用名称,所以这对我来说很不寻常。
【解决方案3】:

如果您是在 javascript 中制作表单和输入,请确保将输入附加到表单中。那是我的问题。

yourForm.appendChild(yourInput);

【讨论】:

    【解决方案4】:

    对我来说,后端配置正确,问题是有效的 JSON 格式,包括变量上的双引号。

    这没用

          const res = await axios.post(serverPath + "/user/login", {
             email: email,
             password: password,
          });
    

    这个 DID 工作(在电子邮件和密码周围加上双引号

          const res = await axios.post(serverPath + "/user/login", {
             "email": email,
             "password": password,
          });
    

    【讨论】:

    • 对于 JavaScript,{"email": email, "password": password} 等同于 {email: email, password: password}
    • 我同意你的观点,但是无论出于什么原因,当 axios 解析这个结果时,一个有效,一个无效。我没有解释 - 只是发布它可能会节省某人的时间。
    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 2022-01-26
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多