How do I POST a x-www-form-urlencoded request using Fetch? How do I POST a x-www-form-urlencoded request using Fetch? javascript javascript

How do I POST a x-www-form-urlencoded request using Fetch?


You have to put together the x-www-form-urlencoded payload yourself, like this:

var details = {    'userName': 'test@gmail.com',    '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.


Even simpler:

fetch('https://example.com/login', {    method: 'POST',    body: new URLSearchParams({        'userName': 'test@gmail.com',        'password': 'Password!',        'grant_type': 'password'    })});

Docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch


Use URLSearchParams

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

var data = new URLSearchParams();data.append('userName', 'test@gmail.com');data.append('password', 'Password');data.append('grant_type', 'password');