Home > Software engineering >  How to post body data using Fetch API?
How to post body data using Fetch API?

Time:03-30

Below is the curl command that gives back the response successfully upon importing and running in postman.

    curl --request POST \
--data "grant_type=password" \
--data "username=test" \
--data "password=xyz1234" \
--data "scope=write" \
--data "client_id=test" \
--data "client_secret=test12" \
"https://example.com/access_token"

Below is how I am sending data using fetch api in my js code.

       const response = await fetch ('https://example.com/access_token', 

  {
    'credentials' : 'include',
     method: 'POST',
     headers: {
      'Content-Type': 'application/json',
      },
     body: JSON.stringify({ grant_type:'password',username:'test',password:'xyz1234',scope:'write',client_id:'test',client_secret:'test12'}),
})

However the equilavent curl which is generated after copying from chrome developer tools is below.

curl --request POST \
--data-raw '{"grant_type":"password","username":"test","password":"xyz1234","scope":"write","client_id":"test","client_secret":"test12"}'
"https://example.com/access_token"

I suspect that the body data is not constructed in the correct format. This may be leading to a 400 error code response. How should I send the data using fetch api equilavent to working curl command?

CodePudding user response:

Looking at the curl your data does seem to be URL encoded. So as it's not expecting JSON don't serialize it to a JSON string.

const headers = new Headers({
  "Content-Type": "application/x-www-form-urlencoded"
});

const urlencoded = new URLSearchParams({
  "grant_type": "password",
  "username": "test",
  "password": "xyz1234",
  "scope": "write",
  "client_id": "test",
  "client_secret": "test12",
});

const opts = {
  method: 'POST',
  headers: headers,
  body: urlencoded,
};

fetch("https://example.com/access_token", opts);

EDIT

As @Kaiido mentioned in the comments. It is not necessary to set the Content-Type header explicitly as the browser will do that automatically, but I have done it here to show you that it should not be set to application/json but to application/x-www-form-urlencoded.

  • Related