首页 > 解决方案 > 请求失败,状态码为 401,仅适用于 IOS 上的 React Native Expo,但在其他任何地方都可以使用

问题描述

我正在使用带有 Expo SDK 的 React Native。我在获取 API(GET 请求)时遇到 IOS 模拟器问题

我已经尝试过 PostMan,在 Android 上它工作得很好,但在 IOS 上它只是抛出

在 iPhone 11 上运行应用程序。

Request failed with status code 401
- node_modules/axios/lib/core/createError.js:15:17 in createError
- node_modules/axios/lib/core/settle.js:16:9 in settle
- node_modules/axios/lib/adapters/xhr.js:52:6 in handleLoad
- node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:567:4 in setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in __didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue

下面是我的 GET 请求函数

const token = await AsyncStorage.getItem("userToken");
const auth_token = 'Token ' + token
axios
      .get("http://127.0.0.1:8001/api/user-info", {
        headers: {
        "Authorization": auth_token,
      }
    })
      .then(function (response) {
        console.log(response)
        const groupData = {};
        groupData["groupName"] = response.data.user.group;
        groupData["userName"] = response.data.user.username;
        groupData["jobTitle"] = response.data.user.job_title;
        console.log(groupData);
        groupName(groupData);
      })
      .catch(function (error) {
        console.log(error)
      });

我也做了调试请求,我正在获取,我不知何故知道 request.headers 中没有授权

这是我的 request.headers 但授权不存在

{'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip, deflate', 'Host': '127.0.0.1:8001', 'Content-Type': 'application/json;charset=utf-8', 'Content-Length': '47', 'Connection': 'keep-alive', 'Accept-Language': 'en-us', 'User-Agent': 'Expo/2.16.0.108985 CFNetwork/1128.0.1 Darwin/19.6.0'}

我还想补充一件事,Login post API 在 iPhone Simulator 上运行良好,但在其他 GET 请求上运行良好

标签: pythondjangoiphonereact-nativeexpo

解决方案


401 表示身份验证无法正常工作(来自 react-native)。请控制台记录您在手机中使用的令牌并尝试在 Postman 中使用它,我很确定控制台日志将是null. 您的标头也没有显示正在传递的任何类型的授权令牌。

另外,你有:

auth_token = 'Token ' + token

应该: const auth_token = 'Token ' + token;


推荐阅读