Search code examples
react-nativeoauth-2.0requestaxiosaccess-token

Axios React Native Token request from fatsecret.com


I need to fetch an Oauth2.0 token from the fatsecret.com API, and would like to save it.

I have a little function to request a token but keep on getting an error 400...

If you could tell me how to fix this even maybe using fetch(), I would really appreciate it..

I have been stuck on this for so long...

Thanks in advance.

Postman token call

const clientId = 'xxxxxxxxxx';
const clientSecret = 'xxxxxxxx';

async authorize () {
   const data = {
      auth: {
         user : clientId,
         password : clientSecret
      }
    }
    const config = {
      headers: { 
        'content-type': 'application/json'
      },
      'grant_type': 'client_credentials',
      'scope' : 'premier',
      json: true
    }
    const res = await axios.post('https://oauth.fatsecret.com/connect/token', {data}, [{config}]);
    console.log(res.data);
  }

Solution

  • Try to use fetch like this:

        const clientId = 'xxxxxxxxxx';
        const clientSecret = 'xxxxxxxx';
        authorize () {
            let formData = new FormData();
            formData.append('grant_type', 'client_credentials');
            formData.append('user', clientID);
            formData.append('password', clientSecret);
            formData.append('scope', 'basic');
    
            fetch('https://oauth.fatsecret.com/connect/token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: formData
            })
            .then((response) => response.json())
            .then((responseData) => {
                console.log(responseData);
            });
    }
    

    Hope this helps!