在React-Native App中将Axios GET与Authorization Header一起使用 [英] Using Axios GET with Authorization Header in React-Native App

查看:294
本文介绍了在React-Native App中将Axios GET与Authorization Header一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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帖子,因此使用querystring .. 所以对于那些可能正在寻找示例代码的人..这是我的完整请求

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 App中将Axios GET与Authorization Header一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆