fetch icon indicating copy to clipboard operation
fetch copied to clipboard

How to set body parameter when method is 'POST' and 'GET'?

Open MrZhang123 opened this issue 8 years ago • 3 comments

I use fetch in my project , when I set method is 'POST' , the body how to set ? in README, i find the body set like this:

  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })

but some article say the body need parameter like this:

body: "firstName=Nikhil&favColor=blue&password=easytoguess"

I have a question ,when the method set 'POST', body can set in two type like these ?

Moreover, when method set 'GET', how to set body ?

MrZhang123 avatar Jun 29 '18 08:06 MrZhang123

Hello, this is a usage question and, as such, not appropriate to open issues about. Please use issues only for bug reports.

GET requests can't have a body. POST requests can have a body which is either a string (such as the result of JSON.stringify), a URLSearchParams instance, a FormData instance, or some of the other types documented in https://github.github.io/fetch/#request-body.

When supplying a string body, you must also set an appropriate content-type header.

fetch('/url', {
  method: 'post',
  body: JSON.stringify(data),
  headers: { 'Content-type': 'application/json' }
})

fetch('/url', {
  method: 'post',
  body: 'firstName=Nikhil&favColor=blue&password=easytoguess',
  headers: { 'Content-type': 'application/x-www-form-urlencoded' }
})

mislav avatar Jun 29 '18 13:06 mislav

how can we set the value in body ? body: 'firstName=Nikhil&favColor=blue&password=easytoguess', if i want to show Nikhil from a variable how can we do that?

tahir-jamil avatar Apr 24 '19 19:04 tahir-jamil

let payload = { username: this.state.username, password: this.state.Password,

}; let data = new FormData(); data.append( "json", JSON.stringify( payload ) ); fetch("YOUR URL", { method: 'post', body: JSON.stringify(data), headers: { 'Content-type': 'application/json' } }) .then(function(res){ return res.json(); }) .then(function(data){ alert( JSON.stringify( data ) ) console.warn(data) })

}

Babar-Memon avatar Apr 25 '19 06:04 Babar-Memon