如何在本机反应中从 api 获取访问令牌 [英] How to get access token from api in react native
问题描述
我正在使用 react native,我想从 django 中使用 oAuth 2 身份验证创建的 api 获取访问令牌
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
请帮忙提前致谢
推荐答案
尝试了 response.json() 但给出了相同的授权类型错误
- 这是来自您的 oauth 服务器的答案.
tried response.json() but giving same error of grant type
- this is answer from Your oauth server.
response.json()
将您的响应数据转换为 json 解码字符串.
response.json()
transform your response data into json decoded string.
将您的代码更改为:
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);
});
这篇关于如何在本机反应中从 api 获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!