简体   繁体   English

在React组件故障中使用Node-Fetch发布数据

[英]Posting data using node-fetch in a react component malfunction

I'm simply trying to post json data to an express server using node-fetch. 我只是试图使用node-fetch将json数据发布到快速服务器。 I know the post function in the server works because I've tested it in git bash. 我知道服务器中的post函数可以工作,因为我已经在git bash中对其进行了测试。 I'm also doing this in a react component. 我也在React组件中这样做。

Here's the fetch code: 这是获取代码:

   addBug(bug) {
    let bugsModified = this.state.bugs.slice()
    bug.id = this.state.bugs.length + 1
    bugsModified.push(bug)

    fetch('http://localhost:3000/api/bugs', {method: 'POST', body: bugsModified})
      .then(res => res.status === 200 && this.setState({bugs: bugsModified}))
  }

The {body: bugsModified} doesn't seem to send the server anything. {body:bugsModified}似乎没有向服务器发送任何内容。 Here's the code from the server: 这是来自服务器的代码:

app.use(bodyParser.json())

app.post('/api/bugs', (req, res) => {
  const bug = req.body
  bugs.push(bug)
  res.json(bug)
})

app.listen(3000, () => console.log('connected...'))

If anyone can help me figure out how to post actual data using node-fetch, it would be greatly appreciated. 如果有人可以帮助我弄清楚如何使用node-fetch发布实际数据,将不胜感激。

FYI I would ensure that your content headers are populated: 仅供参考,我将确保填充您的内容标头:

headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': new Buffer(body).length
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM