Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I send a POST request with Fetch?

POST request using fetch API: To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we'll do a POST request on the same JSONPlaceholder and add a post in the posts. It'll then return the same post content with an ID.

How do you send X www form URL-encoded in react?

You have to put together the x-www-form-urlencoded payload yourself, like this: The ES5 way: var formBody = [];for (var key in body) { var encodedKey = encodeURIComponent(key); var encodedValue = encodeURIComponent(body[key]); formBody. push(encodedKey + '=' + encodedValue);}formBody = formBody.


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.


Even simpler:

fetch('https://example.com/login', {
    method: 'POST',
    body: new URLSearchParams({
        'userName': '[email protected]',
        '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', '[email protected]');
data.append('password', 'Password');
data.append('grant_type', 'password');

Just did this and UrlSearchParams did the trick Here is my code if it helps someone

import 'url-search-params-polyfill';
const userLogsInOptions = (username, password) => {



// const formData = new FormData();
  const formData = new URLSearchParams();
  formData.append('grant_type', 'password');
  formData.append('client_id', 'entrance-app');
  formData.append('username', username);
  formData.append('password', password);
  return (
    {
      method: 'POST',
      headers: {
        // "Content-Type": "application/json; charset=utf-8",
        "Content-Type": "application/x-www-form-urlencoded",
    },
      body: formData.toString(),
    json: true,
  }
  );
};


const getUserUnlockToken = async (username, password) => {
  const userLoginUri = `${scheme}://${host}/auth/realms/${realm}/protocol/openid-connect/token`;
  const response = await fetch(
    userLoginUri,
    userLogsInOptions(username, password),
  );
  const responseJson = await response.json();
  console.log('acces_token ', responseJson.access_token);
  if (responseJson.error) {
    console.error('error ', responseJson.error);
  }
  console.log('json ', responseJson);
  return responseJson.access_token;
};