Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/x/...

created at 02-06-2022 views: 34

problem

  • backend: django REST framework
  • frontend: React/Next.js

had this problem when posting from http://localhost:3000.The complete error message should be like:

Cross-Origin Request Blocked: 
The Same Origin Policy disallows reading the remote resource 
at http://127.0.0.1:8000/api/x/. 
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Status code: 200.

solution

don't know other types of backend, but for django, the solution is to implement the plugin django-cors-headers:

I haven't set anything for headers in the frontend

 pip install django-cors-headers

add to the installed apps

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]
MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware", # add this
    "django.middleware.common.CommonMiddleware",
    ...,
]

set allowed origins:

in my case its http://localhost:3000:

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
]
created at:02-06-2022
edited at: 02-06-2022: