I need do a post request with fetch like this in Postman.
And what I've tried :
let formData = new FormData();
formData.append('username', String(username));
formData.append('password', String(password));
let init = {
method: 'POST',
header:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData
}
fetch(url, init)
It's successful in Postman but failed with fetch that return a 400 error with no param. Hope some helps , thanks
So I changed my code
var details = {
'username': '123',
'password': '123',
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
let init = {
method: 'POST',
header:{
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}
fetch(url, init)
But get a same error
console the formBody:
username=123&password=123
My headers key was wrong ,that was the fault
should be:
let init = {
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}
instead of
let init = {
method: 'POST',
header:{
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}