Home > Back-end >  React native API request with fetch() to getmati API respond well in postman, but not working in App
React native API request with fetch() to getmati API respond well in postman, but not working in App

Time:11-25

I am trying to integrate mati api for KYC flow into my React native app. In order to get auth token, I referenced the documentation below. https://docs.getmati.com/reference/authentication Testing in postman works fine and got the response of auth_token. However, in the React native code, it got 400 error. Please help me figure this out. The code snippet:

const myoptions = {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization:
          'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
      },
      body: new URLSearchParams({grant_type: 'client_credentials'}),
    };

    fetch('https://api.getmati.com/oauth', myoptions)
      .then(response => response.json())
      .then(response => console.log(response))
      .catch(err => console.error(err));

The error is:

 LOG  {"code": 400, "message": "Missing parameter: `grant_type`", "name": "invalid_request", "status": 400, "statusCode": 400}

CodePudding user response:

From the documentation you mentioned it seems like its accepting form data and you are sending search params. Try this

const formData = new FormData();
formData.append("grant_type","client_credentials");

const myoptions = {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization:
      'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
  },
  body: formData,
};

fetch('https://api.getmati.com/oauth', myoptions)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

CodePudding user response:

I found the error and figured out as below.

const body = new URLSearchParams({grant_type: 'client_credentials'});
const myoptions = {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization:
          'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
      },
      body: body.toString(),
    };

    fetch('https://api.getmati.com/oauth', myoptions)
      .then(response => response.json())
      .then(response => console.log(response))
      .catch(err => console.error(err));

In react native, we must send the body as string, it works well and get the right response. Thank you.

  • Related