【问题标题】:React requests with axios on DRF api throws error Forbidden (CSRF cookie not set.)在 DRF api 上使用 axios 响应请求会引发错误 Forbidden (CSRF cookie not set.)
【发布时间】:2019-03-16 16:57:02
【问题描述】:

这是我的反应 Js 代码:

export function loginUser({ email, password }, history) {
  return (dispatch) => {
    axios({
      url: URL_LOGIN_BASE,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
      },
      // withCredentials: true,
      data: { "email": email, "password": password }
    }).then(response => {
      dispatch(setAuthentification(true));
      history.push("/dashboard");
      console.log(response);
    }).catch(err => {
      console.log(err);
    });
  };
}

这里是我的服务器配置(settings.py):

ALLOWED_HOSTS = [
    "127.0.0.1",
        "localhost",
    "192.168.0.1",
    "mockbic.spnnjy4rjm.eu-west-3.elasticbeanstalk.com"
]

CORS_ORIGIN_WHITELIST = (
    'localhost:3000',
    '127.0.0.1:3000',
)

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'Access-Control-Allow-Origin',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'mock-bic-token',  # IMPORTANT
)

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "storages",
    "datacollection.apps.DatacollectionConfig",
    "corsheaders",
]

所以我有后端错误:禁止(未设置 CSRF cookie。):/

backend error

请这个问题是最新的,但所有尝试的解决方案都不能解决我的问题......帮助!

【问题讨论】:

  • 请在您的问题中添加您的错误文本,不要添加图像,因为它将来可能无法使用,并且文本更容易参考。
  • 您提到所有尝试过的解决方案都不能解决您的问题,您能否将您已经尝试过的解决方案也添加到您的问题中?这样,您可以获得更好的问题答案,否则您将获得您可能已经尝试过的解决方案。
  • 我使用了 "withCredentials=true", credentials: 'include' 并添加 axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken";波纹管 axios 导入但没有解决问题
  • 错误是:Forbidden (CSRF cookie not set.): / [11/Oct/2018 18:37:23] "POST / HTTP/1.1" 403 2868

标签: django reactjs axios csrf


【解决方案1】:

您需要在请求标头中添加csrf 令牌。

export function loginUser({ email, password }, history) {
      return (dispatch) => {
      axios({
        url: URL_LOGIN_BASE,
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "X-CSRFToken" : "TOKEN FROM YOUR COOKIES" 
        },
        // withCredentials: true,
        data: { "email": email, "password": password }
      }).then(response => {
        dispatch(setAuthentification(true));
        history.push("/dashboard");
        console.log(response);
     }).catch(err => {
      console.log(err);
    });

// 下面的函数从cookies中返回csrftoken。

  export const getCsrfToken = () => {
      const csrf = document.cookie.match('(^|;)\\s*csrftoken\\s*=\\s*([^;]+)');
      return csrf ? csrf.pop() : '';
    };

【讨论】:

  • 谢谢,但它仍然不适合我!我这样设置:axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken";但总是相同的后端响应 403
  • 我在我的项目中使用 csrf。我只是在标题中传递它.. axios.defaults.xsrfCookiaName 中没有任何内容.. 查看我更新的答案以从 cookie 中获取 csrftoken
  • 糟糕!已解决... URL 错误。正确设置后它工作正常!!!
猜你喜欢
  • 2019-06-16
  • 2022-01-12
  • 2022-01-26
  • 2021-05-28
  • 2018-03-16
  • 1970-01-01
  • 2019-07-05
  • 2021-10-30
  • 1970-01-01
相关资源
最近更新 更多