How to get access token from api in react native

2019-07-23 18:49发布

问题:

I am using react native and i want to get the access token from api which is created in django using oAuth 2 authentication

i am passing all the details which are required but i do not know why i am getting error of unsupported grant type

fetch('MyApiUrl', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: JSON.stringify({
                'grant_type': 'password',
                'username': 'MyUserNameSettedInApi',
                'password': 'PasswordSettedInApi',
                'client_id': 'MyClientId',
                'client_secret': 'MyClientSecret',
                'scope': 'read Write'
            })
        })
            .then((response) => response)     <----tried response.json() but giving same error of grant type
            .then((responseData) => {
                console.log(responseData);
            })

My expected result is i want access token should display and what i am getting is

Response {type: "default", status: 400, ok: false, statusText: undefined, headers: Headers, …}
headers: Headers {map: {…}}
ok: false
status: 400
statusText: undefined
type: "default"
url: "http://MyUrl"
_bodyInit: "{"error": "unsupported_grant_type"}"
_bodyText: "{"error": "unsupported_grant_type"}"
__proto__: Object

please help thanks in advance

回答1:

tried response.json() but giving same error of grant type - this is answer from Your oauth server.

response.json() transform your response data into json decoded string.

Change Your code to this:

let formData = new FormData();
formData.append('grant_type', 'password');
formData.append('username', 'MyUserNameSettedInApi');
formData.append('password', 'PasswordSettedInApi');
formData.append('client_id', 'MyClientId');
formData.append('client_secret', 'MyClientSecret');
formData.append('scope', 'read Write');

fetch('MyApiUrl', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: formData
})
.then((response) => response.json())
.then((responseData) => {
    console.log(responseData);
});


回答2:

Install qs library

npm install qs

Import it in your app and then you'll be able to send it. Use qs.stringify as shown below

fetch('http://localhost:8888/o/token',
       {
         method: 'POST',
         headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/x-www-form-urlencoded;'
         },
         body: qs.stringify({
           'grant_type': 'password',
            'username': 'MyUserNameSettedInApi',
            'password': 'PasswordSettedInApi',
            'client_id': 'MyClientId',
            'client_secret': 'MyClientSecret',
         })
       })