在DRF api上使用axios响应请求将引发错误(禁止设置CSRF cookie)。

时间:2018-10-11 14:45:32

标签: django reactjs axios csrf

这是我的React 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

请问这个问题是最新的,但是尝试的所有解决方案都无法解决我的问题...

1 个答案:

答案 0 :(得分:0)

您需要在请求标头中添加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);
    });

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

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