Home > Mobile >  how to pass parameters to an http request that call which takes the POST payload as form-data progra
how to pass parameters to an http request that call which takes the POST payload as form-data progra

Time:08-09

I have an HTTP POST request that accepts the body as form-data.

grant_type: client_credentials

when I use this API in an application, I need to pass a client_id and client_secret parameter to this call.

so far I have

   const postRequest = {
      url: 'https://address',
      method: 'POST',
      headers: {
        'authorization': 'Basic xyz',
        'content-type': 'application/x-www-form-urlencoded'
      },
     formData: {
        'grant_type': 'client_credentials'
      }
    };

How do I include the id and secret into this request? I have also tried

 formData: {
     'grant_type' : 'client_credentials',
     'client_id' :'id',
    'client_secret' : 'secret'
  }

that does not work either as stated in How to use FormData for AJAX file upload?

CodePudding user response:

This is an OAuth2 flow, and it's most likely you need to pass this in your Basic authorization header.

  headers: {
    'authorization': 'Basic '   btoa(`${clientId}:${clientSecret}`),
    'content-type': 'application/x-www-form-urlencoded'
  },

It's even better to use a good existing OAuth2 library to handle the heavy lifting. I've open sourced mine:

https://github.com/badgateway/oauth2-client

it would work like this:

const client = new OAuth2Client({
  tokenEndpoint: 'https://address',
  clientId: '...',
  clientSecret: '...',
});
const result = await client.clientCredentials();
  • Related