close

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

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How do I POST a x-www-form-urlencoded request using Fetch? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

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

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

    do I POST a x-www-form-urlencoded request using Fetch If you are using JQuery, this works too..
    fetch(url, { method: 'POST', body: $.param(data), headers:{ 'Content-Type': 'application/x-www-form-urlencoded' } })

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

    do I POST a x-www-form-urlencoded request using Fetch If you are using JQuery, this works too..
    fetch(url, { method: 'POST', body: $.param(data), headers:{ 'Content-Type': 'application/x-www-form-urlencoded' } })

Method 1

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;
};

Method 2

If you are using JQuery, this works too..

fetch(url, {
      method: 'POST', 
      body: $.param(data),
      headers:{
        'Content-Type': 'application/x-www-form-urlencoded'
      }
})

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment