How do I POST a x-www-form-urlencoded request using Fetch?
Even simpler:
fetch('https://example.com/login', {
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'userName': '[email protected]',
'password': 'Password!',
'grant_type': 'password'
})
});
Docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
You have to put together the x-www-form-urlencoded payload yourself, like this:
var details = {
'userName': '[email protected]',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('https://example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
})
Note that if you were using fetch
in a (sufficiently modern) browser, instead of React Native, you could instead create a URLSearchParams
object and use that as the body, since the Fetch Standard states that if the body
is a URLSearchParams
object then it should be serialised as application/x-www-form-urlencoded
. However, you can't do this in React Native because React Native does not implement URLSearchParams
.