【问题标题】:Using Axios GET with Authorization Header in React-Native App在 React-Native 应用程序中使用带有授权标头的 Axios GET
【发布时间】:2017-05-22 00:09:37
【问题描述】:

我正在尝试将 axios 用于带有 API 的 GET 请求,该 API 需要 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);
  });

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

【问题讨论】:

  • console.log('Bearer' + USER_TOKEN) 给出了什么?
  • 它给 Bearer 472397403110(或任何令牌号)
  • console.log(typeof(USER_TOKEN)) 给出了什么?
  • 尝试使用concat。这是字符串连接推荐的javascript方式
  • 使用 concat 没有改变。并且 typeof 给出字符串返回

标签: react-native oauth-2.0 http-headers fetch axios


【解决方案1】:

对于看到这篇文章并可能觉得它有用的其他人...... 我的代码实际上没有任何问题。我犯了请求 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);
  });

【讨论】:

  • 如何在axios中传递多个自定义header
  • axios.get(uri, { headers: { "custom-header-1": "value", "custom-header-2": "value" } })
  • 您是否有使用 Amplify 和 Apigateway 的标头示例? :) 只是问
  • 谢谢!做到了 50。
【解决方案2】:

在我将授权放在单引号中之前无法使其工作:

axios.get(URL, { headers: { 'Authorization': AuthStr } })

【讨论】:

  • 这应该没关系
猜你喜欢
  • 2015-07-24
  • 2020-11-21
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多