Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript fetch()POST请求,数据成为对象键_Javascript_Reactjs_Express_Post_Fetch - Fatal编程技术网

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

Javascript fetch()POST请求,数据成为对象键,javascript,reactjs,express,post,fetch,Javascript,Reactjs,Express,Post,Fetch,是否有人在发送一个POST fetch请求时遇到问题,其中JSON字符串成为接收端的对象键,特别是使用头的{“Content Type”:“application/x-www-form-urlencoded”} 我还尝试使用CircularJSON尝试修复stringify可能创建的任何循环引用,因为在收到JSON时,NodeJS抛出了类型错误 客户端代码: /* Triggered on a button click */ triggerTransfer(product) { let

是否有人在发送一个POST fetch请求时遇到问题,其中JSON字符串成为接收端的对象键,特别是使用头的
{“Content Type”:“application/x-www-form-urlencoded”}

我还尝试使用CircularJSON尝试修复stringify可能创建的任何循环引用,因为在收到JSON时,NodeJS抛出了类型错误

客户端代码:

/* 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,
“标识符”:“CABLE-RJ45-NETWORK-TESTER”,
“说明”:“CABLE-RJ45-NETWORK-TESTER”,
“价格”:50,
“成本”:35,
“供应商”:{
“id”:104,
“标识符”:“,
“名称”:“,
“_信息”:{
“公司”:”
}
},
“_信息”:{
“最新更新”:“2012-08-30T05:37:13Z”,
“更新人”:”
}
}
在服务端接收时,对象如下所示:

{
“{”id“:1127,“标识符”:“CABLE-RJ45-NETWORK-TESTER”,“描述”:“CABLE-RJ45-NETWORK-TESTER”,“价格”:50,“成本”:35,“供应商”:{”id“:104,“标识符”:“名称”:“:”“_信息”:{”公司_href:“}},“_信息”:{”上次更新的“:“更新的人”:“}}”:”
}
请注意,从客户端发送的JSON字符串现在是对象键:(


任何帮助都会非常棒

都很好,通过更改标题并远离编码来修复此问题:

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

您正在将body设置为字符串,而将内容类型设置为form encoded,这没有任何意义。是否要发送键/值对或JSON?我只需要在服务器端访问该对象,您会推荐哪一种方法以及实现此目的的方法?我会将其作为JSON发送,并通过设置corre将body作为字符串读取application/json的ct HTTP头。请参阅