0

There are many solutions on SO for this problem. Some are extremely detailed (e.g. this one). However, although I think I have followed the setup instructions explicitly, I still cannot get it to work. Can someone please point out my error?

js

let endpoint = 'http://192.168.4.28:8000/test-put'
const form_data = new FormData();

form_data.append("payload", payload);

await fetch(endpoint, {
    credentials: "include",
    method: "PUT",
    body: form_data,
    headers: {
        "X-CSRFToken": getCookie("csrftoken"),
    },
})

urls.py

path('test-put/', views.TextPut.as_view()),

views.py

class TextPut(View):
    def put(self, request):
        return {}

settings.py

...
ALLOWED_HOSTS = ['192.168.4.28']
...
CORS_ALLOWED_ORIGINS = [
    'http://localhost:8888',
]

CSRF_TRUSTED_ORIGINS = [
    'http://localhost:8888',
]

CORS_ALLOW_CREDENTIALS = True
...
INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]
...
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ...
    'django.middleware.common.CommonMiddleware',
    ...
]
...
CORS_ALLOW_METHODS = [
    'GET',
    'PUT',
    'POST',
]

This produces the error:

Access to fetch at 'http://192.168.4.28:8000/test-put' from origin 'http://localhost:8888' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Psionman
  • 3,084
  • 1
  • 32
  • 65

1 Answers1

0

Thanks to @Dauros and @Jub0s I now have a minimal set of CORS settings that solve this problem

settings.py

...
# CORS Settings
CORS_ALLOWED_ORIGINS = [
    'http://localhost:8888',
]

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_METHODS = [
    'GET',
    'POST',
]
...
Psionman
  • 3,084
  • 1
  • 32
  • 65