Home > Software engineering >  pass data with fetch()
pass data with fetch()

Time:09-11

How can pass data from frontend to backend using fetch()

I have a button in front end I want when clicked on it Sends a post request to backend so it edit something in the data base NOTE: I am using express.js in backing

CodePudding user response:

You can use axios package as an alternative for fetch as it is more user friendly and easy to use. You can easily send post requests using that. Not only post but all the HTTP request. Hope this helps and please comment further if you have any queries. The reference below explains all.

Reference

CodePudding user response:

You can post data using fetch like this:

// Data to post to our backend
const data = {
  id: 1,
  title: 'myTitle',
}
fetch('http://backend.com/test', {
  method: 'POST',
  body: JSON.stringify(data),
  headers: { 'Content-Type': 'application/json' }
}).then(res => res.json())
  .then(json => console.log(json))

Of course you will need to change the above to use the url for you backend as well as a valid route e.g:

// backend
const app = require('express')()

app.post('/test', (req, res) => {
  // handle post data from client here
  res.send('ok')
})

app.listen(8080)
  • Related