1

been given an API endpoint from one of the backend devs to get back a token to use for future API calls but I'm having issues with the grant_type.

I've been given a username and password and been told to set the grant_type as 'password'.

I'm using Axios, this is was first attempt at getting this to work:

const data = {
    Username: 'Test',
    Password: 'TestPassword',
    grant_type: 'password'
};

const config = {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
};

axios.post('https://example.com/api/token', data, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });

This returns an error (400) of unsupported grant type.

Reading up online, someone recommended using the QS package to stringify the data:

const creds = qs.stringify({
    Username: 'Test',
    Password: 'TestPassword',
    grant_type: 'password'
});

This however gives me CORS problems (oddly). By this, I mean using the stringify method I get CORS, but don't get CORS errors without it.

How should grant_type be passed into the Axios post?

Is there a correct way to pass the grant_type via fetch or Axios?

Lovelock
  • 7,689
  • 19
  • 86
  • 186
  • 1
    "This however gives me CORS problems (oddly)." — What problems, specifically (quote error messages!)? Why oddly? CORS problems are normal for cross-origin requests. What has the backend dev done to grant permission? – Quentin Feb 06 '19 at 12:07
  • You can use the Network pane in devtools to examine the request, and check the request headers. If you only get a CORS error when you use the QS package, that suggests the browser is first sending a CORS preflight OPTIONS request in that case, due to the QS package call having added one or more request headers to the request which aren’t added otherwise. If so, the value of the Access-Control-Request-Headers request header there will tell you which headers are triggering the browser to do that preflight. The browser should also be logging an error in the devtools console with the same info. – sideshowbarker Feb 08 '19 at 02:27

0 Answers0