【发布时间】:2020-02-21 19:45:08
【问题描述】:
我使用 django-cors-headers 3.1.1 来处理我的 Django 后端和 Javascript 前端应用程序之间的请求和响应。传输是不安全的(即 http,不是 https)。
在本地托管时,一切正常。但是在服务器上部署后,我不再看到 CORS 标头了。
错误信息:
Access to XMLHttpRequest at 'http://[HOST_IP]/api/assets/' from origin 'http://my_custom_domain.eu' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我的 nginx 配置如下:
server {
listen 80;
server_name [HOST_IP];
location / {
include proxy_params;
proxy_pass http://unix:/home/ubuntu/[path_to_app]/app.sock;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, PUT, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 86400;
if ($request_method = 'OPTIONS') {
add_header 'Content-Type' 'text/html; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'PUT') {
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
}
location /static/ {
autoindex on;
alias /home/ubuntu/[path_to_app]/site/static/;
}
}
django-cors-headers 的设置现在在开发和生产中是相同的:
INSTALLED_APPS = (
…
"corsheaders",
…
)
MIDDLEWARE = [
…
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
…
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = ['DELETE','GET','OPTIONS','PATCH','POST','PUT']
在客户端,我尝试添加“Access-Control-Request-Method”:“PUT”标头,但被浏览器拒绝。客户通话中注意到异常:
axios({
method: 'put',
url: `${this.backendUrl}/api/assets/`,
data: formData,
headers: {
'Content-Type': 'application/octet-stream',
}
})
另外,我是第一次尝试在 Amazon AWS EC2 上托管,所以可能有一些我不知道的必需 AWS 配置。例如,是否需要使用 API 网关启用 CORS? documentation 没有这么说(‘如果您使用 API Gateway Import API,您可以使用 OpenAPI 文件设置 CORS 支持’)。
前端应用程序托管在具有以下 CORS 策略的 S3 存储桶上:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
我在这里缺少什么?是否需要一些服务器端(尤其是 nginx)配置?
我尝试过的其他一些解决方案:
我怀疑请求/响应来源是否正确(例如 APPEND_SLASH 变量)。但是如果是这样的话,本地托管不应该报错吗?
我也尝试过像this question那样设置代理头,但是在不太了解nginx的情况下这注定要失败。
【问题讨论】:
标签: nginx amazon-ec2 cors django-cors-headers