Saturday 23 October 2021

React to django CORS issue

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)


from React to django CORS issue

No comments:

Post a Comment