【问题标题】:Malformed json in request body请求正文中的 json 格式错误
【发布时间】:2018-09-19 10:36:47
【问题描述】:

在我们的 react 应用程序中,我们将在文本区域中输入的 json 字符串发布到快速路由器功能。在客户端,我们使用 axios 将数据发布到 express 路由器。

我们确实在快速路由器功能中接收数据,例如:

const reqData = request.body

但是当我们检查在路由器函数中接收到的数据时,我们传递的 json 被另一个花括号包裹:

{{"user":"emp","comapany":"acme"}}

外部大括号似乎是自动添加的,因此 JSON.parse 失败。

有没有办法避免这种情况?

【问题讨论】:

    标签: json node.js reactjs axios express-router


    【解决方案1】:

    我认为问题在于,当您通常想要提取特定属性时,您使用的是对整个 req.body 的引用。

    从客户端发帖时,使用命名键:

    axios.post(`url`, {
      namedKey: {      // -> call it something suitable to your scenario
        user: 'emp',
        company: 'acme'
      }
    })
    

    在您的快速路由器中,使用同名的 desctructure:

    const { namedKey } = request.body
    

    这也可以通过一一删除属性来解决:

    客户:

    axios.post('url', {
      user: 'emp',    // user key
      company: 'acme' // company key
    })
    

    快速路由器:

    const { user, company } = req.body
    

    这真的取决于你想如何组织它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多