在 React-Native 应用程序中使用带有授权标头的 Axios GET [英] Using Axios GET with Authorization Header in React-Native App
问题描述
我正在尝试将 axios 用于带有需要 Authorization
标头的 API 的 GET 请求.
I'm trying to use axios for a GET request with an API which requires an Authorization
header.
我当前的代码:
const AuthStr = 'Bearer ' + USER_TOKEN;
其中 USER_TOKEN
是所需的访问令牌.这个字符串连接可能是问题,就好像我将其发布为 AuthStr = 'Bearer 41839y750138-391'
,以下 GET 请求有效并返回我想要的数据.
where USER_TOKEN
is the access token needed. This string concatenation may be the issue as if I post this as AuthStr = 'Bearer 41839y750138-391'
, the following GET request works and returns the data I'm after.
axios.get(URL, { 'headers': { 'Authorization': AuthStr } })
.then((response => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
我也尝试将其设置为全局标头,但没有成功.
I also tried setting this as a global header with no success.
推荐答案
对于任何看到这篇文章并可能觉得它有用的人...我的代码实际上没有任何问题.我犯了请求 client_credentials 类型访问代码而不是密码访问代码 (#facepalms) 的错误.仅供参考,我正在使用 urlencoded 帖子,因此使用了查询字符串..所以对于那些可能正在寻找一些示例代码的人..这是我的完整请求
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
非常感谢@swapnil 试图帮助我调试它.
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
这篇关于在 React-Native 应用程序中使用带有授权标头的 Axios GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!