【问题标题】:Express js - request body is emptyExpress js - 请求正文为空
【发布时间】:2015-06-27 04:55:57
【问题描述】:

我刚刚安装了最新版本的模块。我无法获得任何 GET 或 POST 变量。我做错了什么? 节点:v0.12.2

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

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
    res.setHeader('Content-Type', 'text/plain')
    res.write('you posted:\n')
    res.end(JSON.stringify(req.body, null, 2))
});
app.listen(3000,function(){
    console.log("Started on PORT 3000");
})

http://localhost:3000/?token=devvvvv GET 返回: 你发布了: {}

感谢您的回答,但 POST 的问题没有解决... POST token=as123ds on http://localhost:3000/ 在 req.body 中返回空数组 我该如何解决这个问题?

【问题讨论】:

  • 您应该只使用一次登录而不是两次,并使用该登录名来编辑您的问题...

标签: javascript node.js express body-parser


【解决方案1】:

您正在通过查询字符串提交参数并尝试通过请求正文访问它们,在这种情况下 为空。

token 参数将在 request.query 中可用,如下所示:

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.query.token, null, 2))
});

如果您只打算在查询字符串中提交参数,则根本不需要挂载 body-parser 中间件。

【讨论】:

    【解决方案2】:

    您应该使用 req.query:

    req.query
    

    包含路由中每个查询字符串参数的属性的对象。如果没有查询字符串,则为空对象 {}。

    api link

    【讨论】:

    【解决方案3】:

    您正在从请求中解析 JSON,因此来自客户端的 POST 必须在 HTTP 标头中包含 'Content-Type': 'application/json'。如果没有,您将在服务器端有空的request.body

    【讨论】:

    • 谢谢。这帮助很大。
    【解决方案4】:

    bodyparser 模块要求 http 请求的“Content-type”属性等于“application/json”。它不适用于其他值。

    【讨论】:

      【解决方案5】:

      您必须在客户端检查请求内容类型,此链接可能会有所帮助

      Node (Express) request body empty

      这是因为bodyParser解析application/json, application/x-www-form-encoded 和 multipart/form-data,它选择 根据 Content-Type 使用哪个解析器。

      【讨论】:

      • 在您的答案中包含该链接的重要细节可能是个好主意,因为链接可能会随着时间的推移而失效,并且如果/当这种情况发生时,您的答案的含义可能会完全丢失。
      猜你喜欢
      • 2012-04-11
      • 2019-06-26
      • 2019-10-24
      • 2019-02-25
      • 2019-11-04
      • 2021-11-27
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      相关资源
      最近更新 更多