fetch()POST请求,数据成为对象键

时间:2018-08-14 22:44:27

标签: javascript reactjs express post fetch

有人在发送POST提取请求时遇到问题,其中JSON字符串成为接收端的对象密钥,特别是使用{ "Content-Type": "application/x-www-form-urlencoded" }作为标头。

我还尝试使用CircularJSON来尝试解决由于StringJS接收到JSON时会吐出类型错误而造成string化的任何循环引用。

客户端代码:

/* Triggered on a button click */
triggerTransfer(product) {

    let headers = {
        body: CircularJSON.stringify(product),
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        method: "POST"
    }

    this.setState({
        transferState: {
    /* State changes*/
        }
    })

    fetch( _API + '/products/transfer', headers)
        .then(res => {
            return res.json()
        })
        .then((res) => {
            console.log(res)
            this.setState({
                transferState: {
        /* State changes*/
                }
            })
        })
        .catch(err => this.setState({ error: err }))
}

服务器端路由(请注意,我也正在使用body解析器),我知道该路由没有任何作用,但这只是为了调试问题:

router.post('/transfer', async (req,res,next)=>{
  console.log(req.body);
  res.json(req.body);
})

从客户端发送时,JSON字符串如下所示:

{
  "id": 1127,
  "identifier": "CABLE-RJ45-NETWORK-TESTER",
  "description": "CABLE-RJ45-NETWORK-TESTER",
  "price": 50,
  "cost": 35,
  "vendor": {
    "id": 104,
    "identifier": "",
    "name": "",
    "_info": {
      "company_href": ""
    }
  },
  "_info": {
    "lastUpdated": "2012-08-30T05:37:13Z",
    "updatedBy": ""
  }
}

在服务端接收到的对象如下所示:

{
  '{"id":1127,"identifier":"CABLE-RJ45-NETWORK-TESTER","description":"CABLE-RJ45-NETWORK-TESTER","price":50,"cost":35,"vendor":{"id":104,"identifier":"","name":"","_info":{"company_href":""}},"_info":{"lastUpdated":"","updatedBy":""}}': ''
}

请注意,从客户端发送的JSON字符串现在是对象密钥:(

任何帮助都会很棒

1 个答案:

答案 0 :(得分:0)

很好,通过更改标题并逐步远离编码来解决此问题:

    let headers = {
        body: CircularJSON.stringify(product),
        headers: { "Content-Type": "application/json" },
        method: "POST"
    }