6

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)
Pankaj
  • 9,749
  • 32
  • 139
  • 283

5 Answers5

4

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',
]
Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • Damn, I was going to suggest replacing the "whitelist" field with the updated one and removing the protocol from the allowed_hosts. BTW, you should try setting `CORS_ORIGIN_ALLOW_ALL = False` to make sure that your allowed origins setting works properly. – Jeff Oct 21 '21 at 13:49
  • Everything works perfectly with this setting. – Pankaj Oct 21 '21 at 14:36
  • 2
    Please add a description of changes that has been made to make this work. – Shahriar Rahman Zahin Dec 12 '21 at 07:07
0

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/'

Shahriar Rahman Zahin
  • 624
  • 1
  • 11
  • 23
0

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']
0

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'
]

-1

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

Ruslan Zhomir
  • 842
  • 9
  • 27