0

I have a reactjs project that makes requests using API to django-rest-framework. It was working fine before, but I'm not sure what made it stop working.

I'm already using django-cors-headers.

My settings.py:

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

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

CORS_ALLOW_ALL_ORIGINS = True

My reactjs request:

fetch('/api/user/', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(obj)
})

The error I got in the django terminal:

Forbidden: /api/user/
[06/Oct/2021 01:15:31] "POST /api/user/ HTTP/1.1" 403 58

Error in console and network tabs in reactjs browser:

// console error:
UserPage.js:65 POST http://localhost:3000/api/user/ 403 (Forbidden)

//network error:
Referrer Policy: strict-origin-when-cross-origin

//Preview in Networks tab:
detail: "CSRF Failed: CSRF token missing or incorrect."

UPDATE my reactjs terminal:

Local:            http://localhost:3000
On Your Network:  http://172.22.192.1:3000

When I open my react project using http://172.22.192.1:3000 it works fine, but using http://localhost:3000 it still can't send a POST request.

1
  • 2
    I'm not sure why some downvoted, if I'm missing something let me knwo so I can add it. Commented Oct 5, 2021 at 23:52

1 Answer 1

0

To resolve your issue, you can use CORS_ORIGIN_WHITELIST instead of CORS_ALLOW_ALL_ORIGINS in the Django settings file.

REPLACE :

CORS_ALLOW_ALL_ORIGINS = True

BY :

CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000',  # React default port = 3000
    'http://localhost:8000',  # Django default port = 8000
)
# Change the url to suit your needs.

NB : The CORS_ALLOW_ALL_ORIGINS define to True must allow all origins, but i faced the same issue before and replace it by CORS_ORIGIN_WHITELIST solved it. Then try it.

Update for Django CSRF-TOKEN : This link may solve your issue about csrf_token

Sign up to request clarification or add additional context in comments.

8 Comments

Tried it but no luck.
I added a new error that I found in the networks tab, does this mean that I should add a token?
Are you using SessionAuthentication ? On your api ?
I don't think so, I do have a superuser but when requesting I don't require any login or authentication.
When I opened the browser using this: 172.22.192.1:3000, It worked. But still doesn't work using: localhost:3000
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.