【问题标题】:nodejs npm body parser return empty bodynodejs npm 正文解析器返回空正文
【发布时间】:2018-02-03 05:45:22
【问题描述】:

我正在使用正文解析器示例

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

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

app.use(function (req, res) {

  console.log(req)

  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

但是当我使用邮递员发布数据时,req.body 返回空值。

但正如您在屏幕截图中看到的那样,我有内容 {message:12345}

在帖子正文中。

代码运行没有错误。

但我得到了回应

you posted:
{}

我应该得到的是

you posted:
{message:12345}

我回显出 req 对象,我可以看到 body 是空的。

req: [Circular],
 locals: {},
 [Symbol(outHeadersKey)]: { 'x-powered-by': [Array] } },
body: {} }

有什么建议吗?

【问题讨论】:

    标签: node.js body-parser


    【解决方案1】:

    您需要发送application/json 的内容类型标头。点击 postman 中的“文本”下拉菜单以选择 JSON。

    【讨论】:

    • 谢谢。有用。我的消息也必须是有效的 json 格式。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-05-27
    • 2019-03-01
    • 1970-01-01
    • 2017-01-29
    • 2012-11-04
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    相关资源
    最近更新 更多