简体   繁体   中英

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. I know the post function in the server works because I've tested it in git bash. I'm also doing this in a react component.

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. 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.

FYI I would ensure that your content headers are populated:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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