我正在尝试使用axios来获取带有需要的API的GET请求 Authorization
头。
我目前的代码:
const AuthStr = 'Bearer ' + USER_TOKEN;
哪里 USER_TOKEN
是需要的访问令牌。这个字符串连接可能是问题,就好像我将其发布为 AuthStr = 'Bearer 41839y750138-391'
,以下GET请求工作并返回我之后的数据。
axios.get(URL, { 'headers': { 'Authorization': AuthStr } })
.then((response => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
我也尝试将其设置为全局标题但没有成功。
对于遇到这篇文章的其他人而言,可能会发现它很有用......
我的代码实际上没有任何问题。我错误地请求client_credentials类型访问代码而不是密码访问代码(#facepalms)。
仅供参考我使用urlencoded帖子因此使用查询字符串..
所以对于那些可能正在寻找一些示例代码的人来说......这是我的完整请求
非常感谢@swapnil试图帮我调试这个。
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);
});