在 React-Native 应用程序中使用带有授权标头的 Axios GET

Posted

技术标签:

【中文标题】在 React-Native 应用程序中使用带有授权标头的 Axios GET【英文标题】:Using Axios GET with Authorization Header in React-Native App 【发布时间】: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 给出字符串返回 【参考方案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 )

【讨论】:

这应该没关系

以上是关于在 React-Native 应用程序中使用带有授权标头的 Axios GET的主要内容,如果未能解决你的问题,请参考以下文章

React-native:如何在 React-native 中使用(和翻译)带有 jsx 的 typescript .tsx 文件?

JWT 授权重定向到登录

我无法在带有 redux 的 react-native 中使用地理定位

在带有 typescript 的 react-native 中使用 createRef?

在 iOS 上带有 expo 的 react-native statusBar

如何在带有 TypeScript 的 React-Native 中使用 styled-component 键入无状态功能组件?