如何在 React Native 中使用 Axios 设置授权标头

Posted

技术标签:

【中文标题】如何在 React Native 中使用 Axios 设置授权标头【英文标题】:How to set authorization header with Axios in React Native 【发布时间】:2020-11-21 12:27:01 【问题描述】:

我正在使用 Expo CLI 构建一个 React Native 应用程序,并且我正在尝试使用 Axios 和 redux thunk 将一些用户数据提取到我的 redux 存储中。

我已将 jwttoken 保存在本地。问题是,我无法设置授权标头。尝试不带单引号和双引号的授权:

export const fetchAccount = createAsyncThunk(
    'auth/fetchAccount',
    async (payload,  dispatch, rejectWithValue, getState ) => 
        try 
            const response = await axios.get('/manager/user/account', 
                headers: 
                    "Authorization": "Bearer " + jwt
                ,
            );
            return response.data
         catch (err) 
            if (!err.response) 
                throw err
            
            console.log(err.response)
            return rejectWithValue(err.response.data)
        
    
);

它总是显示 401,“缺少授权标头”。我的后端工作正常,因为 curl 命令有效:

curl -X GET "http://.......eu.pythonanywhere.com/manager/user/account/" -H "accept: application/json" -H "Authorization: Bearer eyJ0e.......0RmsJoBv9M"

我也用console.log()来记录err.response:

Object 
  "config": Object 
    "adapter": [Function xhrAdapter],
    "baseURL": "http://......eu.pythonanywhere.com",
    "data": undefined,
    "headers": Object 
      "Accept": "application/json, text/plain, */*",
      "Authorization": "Bearer eyJ0e.......0RmsJoBv9M",
    ,
    "maxContentLength": -1,
    "method": "get",
    "timeout": 0,
    "transformRequest": Array [
      [Function transformRequest],
    ],
    "transformResponse": Array [
      [Function transformResponse],
    ],
    "url": "/manager/user/account",
    "validateStatus": [Function validateStatus],
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
  ,
  "data": Object 
    "msg": "Missing Authorization Header",
  ,
  "headers": Object 
    "connection": "keep-alive",
    "content-length": "44",
    "content-type": "application/json",
    "date": "Fri, 31 Jul 2020 16:00:53 GMT",
    "server": "PythonAnywhere",
  ,
  "request": XMLHttpRequest 
    "DONE": 4,
    "HEADERS_RECEIVED": 2,
    "LOADING": 3,
    "OPENED": 1,
    "UNSENT": 0,
    "_aborted": false,
    "_cachedResponse": undefined,
    "_hasError": false,
    "_headers": Object 
      "accept": "application/json, text/plain, */*",
      "authorization": "Bearer eyJ0e.......0RmsJoBv9M",
    ,
    "_incrementalEvents": false,
    "_lowerCaseResponseHeaders": Object 
      "connection": "keep-alive",
      "content-length": "44",
      "content-type": "application/json",
      "date": "Fri, 31 Jul 2020 16:00:53 GMT",
      "server": "PythonAnywhere",
    ,
    "_method": "GET",
    "_requestId": null,
    "_response": "
  \"msg\": \"Missing Authorization Header\"

",
    "_responseType": "",
    "_sent": true,
    "_subscriptions": Array [],
    "_timedOut": false,
    "_trackingName": "unknown",
    "_url": "http://.......eu.pythonanywhere.com/manager/user/account",
    "readyState": 4,
    "responseHeaders": Object 
      "Connection": "keep-alive",
      "Content-Length": "44",
      "Content-Type": "application/json",
      "Date": "Fri, 31 Jul 2020 16:00:53 GMT",
      "Server": "PythonAnywhere",
    ,
    "responseURL": "http://........eu.pythonanywhere.com/manager/user/account/",
    "status": 401,
    "timeout": 0,
    "upload": XMLHttpRequestEventTarget ,
    "withCredentials": true,
  ,
  "status": 401,
  "statusText": undefined,

我尝试将标头设置为 axios 默认值,但得到了相同的响应。

向我的后端或任何公共 API 发送不带标头的请求都可以正常工作。

【问题讨论】:

你读过***.com/questions/40988238/…吗? @kinoth 是的,已经尝试过了,但没有任何改变。 【参考方案1】:

Authorization 不应该用引号引起来。只需删除引号,它应该可以工作

.........
.........
.........
        axios.defaults.headers.common['Authorization'] = `Bearer $jwt`;
        const response = await axios.get('/manager/user/account');

.........
.........
.........

【讨论】:

是的,尝试不带单引号和双引号。但还是同样的错误 嘿@MaximilianKromer 你能试试这个吗? 不幸的是一样。也试过直接设置token,也是同样的问题。【参考方案2】:

试试这个

       const config = 
         headers: 
             Authorization: "Bearer " + jwt
         
     ;

     axios.get('/manager/user/account', ...config);

Authorization 不需要双引号

【讨论】:

还是同样的错误。是的,尝试不带单引号和双引号。

以上是关于如何在 React Native 中使用 Axios 设置授权标头的主要内容,如果未能解决你的问题,请参考以下文章

如何在React Native中使用CreateBottomTabNavigator?

如何在 React Native 中的循环中查找

如何在 react-native 中使用 FormData?

如何使用 React-Native 在 iOS 中禁用屏幕截图

React Native:如何使用 expo 在 webview 中制作全屏 youtube 嵌入视频(没有 react-native 链接)

如何在组件 React / React-native 的单独页面中使用动态 graphql(字符串)