React to django CORS issue

Question:

Error Details

enter image description here

Two requests have been generating on button click.

What did I search so far?

Axios blocked by CORS policy with Django REST Framework

CORS issue with react and django-rest-framework

but to no avail

What am I doing?

Submitting POST request from react to DJango API

Django side settings file

CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = [
    "http://127.0.0.1:3000", 
    "http://127.0.0.1", 
    "http://localhost:3000", 
    "http://localhost"
]
CORS_ORIGIN_WHITELIST = [
    "http://127.0.0.1:3000", 
    "http://127.0.0.1", 
    "http://localhost:3000", 
    "http://localhost"
]

INSTALLED_APPS = [
    ......,
    "corsheaders"
]

MIDDLEWARE = [
    .........,
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

React axios request

function authenticate() {
    let body = {
        "email": "ac",
        "password": "def"
    };
    const headers = {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
    }

    axios.post("http://127.0.0.1:8000/login/", body, {
        headers: headers
    })
    .then(function(response) {
        console.log(response.data);
    })
    .catch(function(error) {
        console.log(error);
    });
}

Tried another approach using fetch, but to no avail

function authenticate() {
    let body = {
        "email": "hi",
        "password": "pass"
    };
    const headers = {
        'Content-Type': 'application/json',
    }
    fetch("http://127.0.0.1:8000/login", {
        method: "POST", 
        headers: { 
            "Content-Type": "application/json"
        },
        body: JSON.stringify(body)
    })
    .then(function(response) {
        console.log(response.data);
    })
    .catch(function(error) {
        console.log(error);
    });
}

DJango side method

def Login(request):
    if(request.method == "POST"):
        return JsonResponse({"message" : "Invalid credentials"}, status=401)
Asked By: Pankaj

||

Answers:

Sometimes it happens because of the url pattern. Please check the url pattern whether it requires a slash at the end or not.

Try using 'login' instead of 'login/'

I think, you forgot to provide "mode": "cors" for your requests, didn’t you?
And you have to process on server side "OPTIONS" requests made by browser in Preflight phase.

"Access-Control-Allow-Origin" header should be sent by server in response. You don’t need it in request.

Read a good explanation on "CORS" requests here: https://javascript.info/fetch-crossorigin

And to correctly setup Django read this: How can I enable CORS on Django REST Framework

Answered By: Ruslan Zhomir

Below settings work for me

CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = [
    "127.0.0.1", 
]

CORS_ALLOWED_ORIGINS = [
    "http://127.0.0.1", 
]
CORS_ALLOW_CREDENTIALS = False

INSTALLED_APPS = [
    .....
    "corsheaders"
]


MIDDLEWARE = [
    ......
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]
Answered By: Pankaj

Try removing CORS_ALLOWED_ORIGINS. Just keep CORS_ORIGIN_ALLOW_ALL = True.
This is my setting on real server:

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
  'accept',
  'accept-encoding',
  'authorization',
  'content-type',
  'origin',
  'dnt',
  'user-agent',
  'x-csrftoken',
  'x-requested-with']
CORS_ALLOW_METHODS = ['DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT']
Answered By: Mohsen Hassani

If you want to keep your server endpoints online accessible for your ReactJS application then you should try to set this in Django settings.py file

CORS_ORIGIN_ALLOW_ALL = False

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3000',
    'http://xxx.xxx.xxx.xxx:portNum',
]

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'PATCH',
    'POST',
    'PUT',
]

# Any headers you wanted to be visible by the ReactJS app.
CORS_EXPOSE_HEADERS = [
    'Date'
]

Answered By: nikita_trifan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.