问题 在React-Native App中使用Axios GET和授权标头


我正在尝试使用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);
  });

我也尝试将其设置为全局标题但没有成功。


11972
2018-01-07 07:39


起源

console.log('Bearer'+ USER_TOKEN)给出了什么? - Swapnil
它给予Bearer 472397403110(或任何令牌号码) - Ally Haire
console.log(typeof(USER_TOKEN))给出了什么? - Swapnil
尝试使用 CONCAT。这是字符串连接的推荐javascript方式 - Swapnil
使用concat没有变化。而typeof给出了字符串返回 - Ally Haire


答案:


对于遇到这篇文章的其他人而言,可能会发现它很有用...... 我的代码实际上没有任何问题。我错误地请求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);
  });

14
2018-01-08 00:17



如何在axios中传递多个自定义标头 - Sahir Saiyed
axios.get(uri, { headers: { "custom-header-1": "value", "custom-header-2": "value" } }) - blueprintchris