I'm having a problem with CORS and Django where, when I try to POST a JSON from my app, I get no response but got an error:
Cross-origin request blocked: Same Origin Policy prevents reading of remote resource at http://localhost:8000/converter2/. (Reason: 'access-control-allow-headers' symbol missing in 'Access-Control-Allow-Headers' CORS header during CORS pre-connection).
Also, when I try to connect my Django server logs this: "OPTIONS /converter2/ HTTP/1.1" 200 0. Okay, I'm not receiving 'Access-Control-Allow-Headers' from the server. From all I have read this needs to be solved in server side. So I tried to install django-cors-headers and configure it like the following:
# settings.py
INSTALLED_APPS = [
...
'corsheaders'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = True
Sadly nothing changed. So I tried change the CORS_ORIGIN_ALLOW_ALL to False and add my app origin to CORS_ORIGIN_WHITELIST, just like this:
CORS_ORIGIN_WHITELIST = [
'http://localhost:8000'
]
Again, nothing changed. I tried now to force the headers with the server response, like suggested in this answer:
...
response = HttpResponse(status=201)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type"
return response
Still nothing, I don't know what else I can try. I would appreciate new suggestions, thank you.
Ionic v4, port 8100
Django v2.2.4, port 8000
I don't think this is a front side problem, but I will post the request for reference:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:8000, http://localhost:8100',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Accept': 'application/json'
})
};
this.http.post("http://localhost:8000/converter2/", file, httpOptions)
.pipe(
finalize(() => {
loader.dismiss();
})
).subscribe(res => {
if (res['success']) {
this.presentToast('File uploaded complete')
} else {
this.presentToast('File uploaded failed')
}
});