-1

I have an error on the server (local host is OK)

from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried the following (followed this page How can I enable CORS on Django REST Framework)

pip install django-cors-headers

# Added at the top of MIDDLEWARE
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',

# Added after allowed hosts
CORS_ORIGIN_ALLOW_ALL=True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True

After the changes below I have

You can see the error in browser developer's mode VM87:5553 crbug/1173575, non-JS module files deprecated.

How can I fix the error?

Alex
  • 562
  • 1
  • 6
  • 25
  • 1
    Do you get a CORS error in your browser's Console tab? If so, what does it say. Add the error message to your question. – jub0bs Feb 05 '22 at 16:17
  • did you problem has the same as to https://stackoverflow.com/questions/28046422/django-cors-headers-not-work – muhammadyasin89 Jan 31 '23 at 23:37

1 Answers1

-1

My solution:

sudo vim /etc/nginx/sites-available/default
sudo service nginx restart

Changed file

server{
    server_name www.api.site.ru api.site.ru;

    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,X-token' always;
    if ($request_method = 'OPTIONS') {
        return 204;
    }

    location / {
         proxy_pass http://127.0.0.1:8000;
         proxy_set_header Host $host;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-Proto $scheme;
         proxy_set_header X-Forwarded-Proto https;
         proxy_set_header X-Forwarded-Protocol  $scheme;

         proxy_headers_hash_max_size 512;
         proxy_headers_hash_bucket_size 128;
    }

    access_log /var/log/nginx/ar_access.log;
    error_log /var/log/nginx/ar_error.log;

    listen 80; # managed by Certbot

}
Alex
  • 562
  • 1
  • 6
  • 25