【问题标题】:CORS error: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight responseCORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段身份验证
【发布时间】:2020-02-16 02:29:39
【问题描述】:

注销时出现此错误。 从源“http://localhost:3000”访问“http://127.0.0.1:8000/api/auth/logout/”处的 XMLHttpRequest 已被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段身份验证。

我在 onClick 中调用 auth.js 的注销功能。我不知道为什么刷新页面时会退出。

reducer.js

 case LOGOUT_SUCCESS:
      localStorage.removeItem("token");
      return {
        ...state,
        isAuthenticated: null,
        isLoading: false,
        user: null,
        isFreelancer: false
      };

action/auth.js的注销功能

export const logout = () => (dispatch, getState) => {
  const token = getState().auth.token;

  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };

  if (token) {
    config.headers["Authentication"] = `Token ${token}`;
  }

  axios
    .post("http://127.0.0.1:8000/api/auth/logout/", null, config)
    .then(res => {
      dispatch({ type: LOGOUT_SUCCESS });
    })
    .catch(err => {
      console.log(err.message);
    });
};

我希望立即退出,但每次刷新页面时都会退出。

【问题讨论】:

标签: reactjs


【解决方案1】:

如果您使用的是 Create-React-App,您可以在 package.json 文件中简单地执行此操作:

"proxy": "http://127.0.0.1:8000",

这将是代理请求,浏览器不会阻止响应。

【讨论】:

  • 在这种情况下,您可能需要从服务器更新 cors 策略并将您的 url 添加到 cors 策略中。
  • 标头应该包含来自响应的类似内容 => Access-Control-Allow-Origin: localhost:3000
猜你喜欢
  • 2021-09-26
  • 2016-05-15
  • 2014-02-20
  • 2020-02-27
  • 2017-06-23
  • 2016-04-24
  • 2019-02-21
  • 2021-06-06
  • 2017-12-20
相关资源
最近更新 更多