How to set body parameter when method is 'POST' and 'GET'?
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 ?
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' }
})
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?
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) })
}