简体   繁体   中英

React requests with axios on DRF api throws error Forbidden (CSRF cookie not set.)

This is my react Js code :

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);
    });
  };
}

And here my the server configuration (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",
]

So i have the backend error : Forbidden (CSRF cookie not set.): /

backend error

Please this question is very current but all solutions tried don't resolve my case... Help !

you need to add csrf token in your request headers.

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);
    });

// function below returns csrftoken from cookies.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM