CORS during development without Access-Control-Allow-Origin

独自空忆成欢 提交于 2019-12-24 00:48:53

问题


The server answer with a Access-Control-Allow-Origin value set for the production. Is there a way to be permissive when the requests come from my development server ? Is there a Django setting to disable the cross-origin check when DEBUG=True for example ?

I can't modify the Access-Control-Allow-Origin. The request is made with jquery ajax function.

EDIT:

I've installed https://github.com/ottoyiu/django-cors-headers with pip install django-cors-headers, added the following in my settings.py

if DEBUG:
    INSTALLED_APPS += ('corsheaders', )

CORS_ORIGIN_ALLOW_ALL = DEBUG

And put the middleware :

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
...
}

But I still get the error :

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at _request_url_. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

If I inspect the response header, I don't see any Access-Control-Allow-Origin parameter.


回答1:


Install middleware: https://github.com/ottoyiu/django-cors-headers

In django settings.py add following setting:

DEBUG=True

CORS_ORIGIN_ALLOW_ALL = DEBUG

(if DEBUG is true Access-Control-Allow-Origin will be added to headers in response)




回答2:


To add CORS headers to your response, install this to your django project:

https://github.com/ottoyiu/django-cors-headers

Since you want to connect from local, you cannot whitelist a particular host alone.

To enable CORS only when you have DEBUG=True, you can add corsheaders to your installed apps only when Debug is True:

if DEBUG is True:
     INSTALLED_APPS += ('corsheaders', )


来源:https://stackoverflow.com/questions/40760813/cors-during-development-without-access-control-allow-origin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!