【问题标题】:express.json() is not parsing nested json object. it return [object Object] insteadexpress.json() 没有解析嵌套的 json 对象。它返回 [object Object]
【发布时间】:2021-07-17 07:07:05
【问题描述】:

express.json() 没有解析嵌套的 json 对象。它返回 [object Object]。

express - 4.17.1,

请求标头

Content-Type: application/json;charset=UTF-8

我使用 express.json() 如下。

app.use(express.json());

当我发布没有嵌套对象的数据时。它有效

const data = await this.$axios.$post(`user/update/${this.username}`, {confirmationCode:  "code"});

现在 req.body.confirmationCode 是“代码”。

但如果我发布嵌套的 json 对象。它不起作用

const data = await this.$axios.$post(`user/update/${this.username}`, {confirmationCode: { mobile: "code"}});

现在 req.body.confirmationCode.mobile 未定义。 req.body.confirmationCode 是 [object Object]。

【问题讨论】:

  • 看起来您正在将req.body.confirmationCode 转换为字符串。 req.body.confirmationCode.toString() -> [object Object].
  • 无法复制。

标签: node.js json express


【解决方案1】:

我注意到有几个人在没有实际回答问题的情况下对此表示反对。我也有这个问题,结果证明这是一个简单的解决方法。尝试通过 JSON.stringify() 传递对象,看看是否有帮助。

示例代码:

`console.log(`My Test req.body:  ${JSON.stringify(req.body)} \n`);`

此外,如果您将 JSON 作为参数传递给函数,请不要尝试将其传递为纯文本(字符串格式)。而是像我一样使用它,req.body,或者创建一个新对象并发送对象的变量而不是字符串版本。

【讨论】:

    猜你喜欢
    • 2018-12-17
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多