0

My frontend and the backend are decoupled and client runs on localhost:3000 and the backend runs at localhost:8000. I have the csrf and the refresh tokens and I set them as cookies on the server side. Now I need those cookies on the client side. This is the react code that I have written :

fetch('http://localhost:8000/api/Acutes/SignIn/', {
      method: 'POST',
      headers: {
      'Content-Type': 'application/json',
       'withCredentials': 'true'
       },
       body: JSON.stringify(values)
       })
       .then(data => data.json())
       .then(data =>{
             console.log(data)
         })
       .catch(error =>{
         console.error(error);
         })

Django settings

CORS_ORIGIN_WHITELIST = [
    "http://localhost:9001",
    "http://localhost:3000"
]

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'withCredentials'
]

The error that seems to be there upon using this is as follows.

Access to fetch at 'http://localhost:8000/api/Acutes/SignIn/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field withcredentials is not allowed by Access-Control-Allow-Headers in preflight response.

How should i deal with this error and get my cookies onto the client side?TIA

otaku_weeb
  • 77
  • 5
  • You need to update it backend – Shubham Verma Aug 23 '20 at 11:42
  • @ShubhamVerma I added 'withCredentials' to the backend but only csrf token is made available in the cookies even though none of the tokens are HTTPonly – otaku_weeb Aug 23 '20 at 11:49
  • Its **cors issue**. I have no idea about django. Basically you need to allow for localhost or different port. Its not frontend issue – Shubham Verma Aug 23 '20 at 11:51
  • Have you checked this question? https://stackoverflow.com/questions/32500073/request-header-field-access-control-allow-headers-is-not-allowed-by-itself-in-pr You could try removing the withCredentials header field to see if the basic request is allowed. – Matt Dale Aug 23 '20 at 14:51
  • Replace the `CORS_ORIGIN_WHITELIST = [...]` with `CORS_ORIGIN_ALLOW_ALL = True` and let us know the behaviour. Thanks. – MwamiTovi Aug 25 '20 at 02:57

1 Answers1

0

I had a similar issue and to get rid of it I made the following changes- add the django-cors-headers package to your project using - pip install django-cors-headers Add the following to settings.py -

CORS_ORIGIN_WHITELIST = ['http://localhost:3000']

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL=True

CSRF_TRUSTED_ORIGINS = ['http://localhost:3000']

MIDDLEWARE = [
           'corsheaders.middleware.CorsMiddleware',
             ....
              ]

INSTALLED_APPS = [
               ....
             'corsheaders',
               .....
                ]

TO get the csrf token I added a separate api-

from django.middleware.csrf import get_token
def csrf(request):
return JsonResponse({'csrfToken': get_token(request)})

Now in the JS code you can get the csrf token value as follows-

async function getCsrfToken() {
  var csrfToken=getCookie('csrftoken');
  if (csrfToken === null) {
    const response = await fetch(`${API_HOST}/csrf/`, {
      credentials: 'include',
    });
    const data = await response.json();
    csrfToken = data.csrfToken;
  }
  document.cookie = "csrfToken="+csrfToken;
};

I hope this solves your problem