Skip to main content
 首页 » 编程设计

python之django-cors-headers 根本不工作

2025年01月19日38sxdcgaq8080

好吧,最初我忘记了中间件类,但在添加它之后工作正常(一周前)。

现在,我回到我的工作站,我发现它再次无法工作。

ACCESS_CONTROL_ALLOW_ORIGIN header 根本没有设置。

我已经尝试了所有方法,将中间件放在顶部,在 CommonMiddleware 之前,但它不起作用。

这是我的setting.py 文件:

DEBUG = True 
 
ALLOWED_HOSTS = ['*'] 
 
# Application definition 
INSTALLED_APPS = [ 
    'account', 
    'corsheaders', 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
    'social_django', 
] 
 
# if DEBUG: 
#     INSTALLED_APPS += 'corsheaders', 
#     MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', ] 
# else: 
#     MIDDLEWARE = [] 
 
MIDDLEWARE = [ 
    'django.middleware.security.SecurityMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'corsheaders.middleware.CorsMiddleware', 
    'django.middleware.common.CommonMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'django.middleware.clickjacking.XFrameOptionsMiddleware', 
] 
 
CORS_ORIGIN_ALLOW_ALL = DEBUG 

这是我得到的回应:

Date: Sun, 14 Jan 2018 09:35:09 GMT 
Server: WSGIServer/0.1 Python/2.7.14+ 
X-Frame-Options: SAMEORIGIN 
Content-Type: text/html; charset=utf-8 
Content-Length: 146 

请您参考如下方法:

仅当请求中存在 origin header 时,

Access-Control-Allow-Origin 才会包含在响应中。

浏览器会自动添加此 header ,因此您不应在使用您的 API 的网页上看到 CORS 错误。

对我来说,这个请求没有返回Access-Control-Allow-Origin:

curl -v -H "Content-Type: application/json"localhost:80/status

而这个是:

curl -v -H "Content-Type: application/json"-H "origin: *"localhost:80/status

GitHub页面上的答案: https://github.com/adamchainz/django-cors-headers/issues/438