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

All*_*ire 23 fetch http-headers oauth-2.0 react-native axios

我正在尝试使用axios来获取带有需要Authorization标头的API的GET请求.

我目前的代码:

const AuthStr = 'Bearer ' + USER_TOKEN;
Run Code Online (Sandbox Code Playgroud)

其中,USER_TOKEN被访问令牌需要.这个字符串连接可能是问题,好像我发布这个AuthStr = 'Bearer 41839y750138-391',以下GET请求工作并返回我之后的数据.

axios.get(URL, { 'headers': { 'Authorization': AuthStr } })
  .then((response => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });
Run Code Online (Sandbox Code Playgroud)

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

All*_*ire 33

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

  • `axios.get(uri,{headers:{"custom-header-1":"value","custom-header-2":"value"}}) (8认同)

小智 6

除非我将授权放在单引号中,否则无法使其正常工作:

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

  • 这应该不重要 (3认同)