【问题标题】:Weird, Request failed with status code 400奇怪,请求失败,状态码 400
【发布时间】:2021-11-09 00:26:42
【问题描述】:

我正在使用 Axios 向服务器发送请求。这是我使用的实例:

export default axios.create({
  baseURL: "https://wagal.com",
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": `Bearer ${store.getState().auth.userData.token}`,
  },
});

这是我如何使用上述实例来启用和禁用 2fa:


function switchTfa(data) {
  if (data) {
    return (dispatch) => {
      return api_request
        .post("/api/user/tfa/enable", {})
        .then((response) => {
          dispatch(isLoading(false));
          dispatch(
            userData({
              tfa_enabled: data,
              user_token: store.getState().auth.userData.token,
            })
          );
          console.log("Success");
        })
        .catch((error) => {
          dispatch(isLoading(false));
          console.log(`error.message`, error.message);
        });
    };
  } else {
    return (dispatch) => {
      dispatch(isLoading(true));
      return api_request
        .post("/web-api/user/tfa/disable", {})
        .then((response) => {
          dispatch(isLoading(false));
          dispatch(
            userData({
              tfa_enabled: data,
              user_token: store.getState().auth.userData.token,
            })
          );
          console.log("Success");
        })
        .catch((error) => {
          dispatch(isLoading(false));
          console.log(`error.message`, error.message);
        });
    };
  }
}

现在,如果我发送此请求,我会收到以下错误:

Request failed with status code 400

如果我在 Axios 实例中取消引用“授权”,它会起作用

export default axios.create({
  baseURL: "https://wagal.com",
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    Authorization: `Bearer ${store.getState().auth.userData.token}`,
  },
});

现在,如果我重新加载应用程序并发送请求,它会抛出这个 400 错误,但如果我再次用引号包裹“授权”,它会发送请求,奇怪!!!

为什么每次重新加载后我有时会通过引用和有时通过取消引用“授权”得到 400 个错误?

谢谢

【问题讨论】:

  • 当然引号或不直接与任何行为变化无关;它们只是触发热重载或刷新,进而导致您看到的行为。

标签: javascript reactjs react-native axios


【解决方案1】:

这是因为存储不是持久的。正如我可以从您的代码中想象的那样,状态不是全局维护的,例如 Redux,因此当您刷新时,商店是空的。 理想情况下,当我们希望为 API 调用发送访问令牌时,您将有两种选择,

  1. 将访问令牌以加密形式存储在本地存储中
  2. 使用浏览器内存存储获取更安全的访问令牌

您可以在这里阅读更多信息:https://auth0.com/docs/security/data-security/token-storage#browser-in-memory-scenarios

【讨论】:

  • 非常感谢,我正在使用 redux,当我发送请求时,我打开了 React Native Debugger,我可以看到令牌存在并存在的 Redux 状态,我什至将令牌记录到确保令牌存在并且确实存在。
猜你喜欢
  • 2017-06-02
  • 2019-09-29
  • 2020-10-03
  • 2020-10-21
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
相关资源
最近更新 更多