【发布时间】:2020-12-19 07:13:22
【问题描述】:
我是一个非常新的用户,所以如果我违反任何规则,请提前道歉。这是我面临的问题,需要建议。
我有一个 Chrome 扩展程序,它与 Gmail 一起使用,并通过 Rails 应用程序的 Phusion Passenger 服务器使用我在 nginx 上运行的 Web 服务器的 API。
我的 Nginx 版本是 nginx 版本:nginx/1.15.8,Phusion Passenger 版本是 Phusion Passenger Enterprise 6.0.1
我在 nginx 中的 CORS 设置如下:
####### CORS Management ##########
add_header 'Access-Control-Allow-Origin' 'https://mail.google.com,https://*.gmail.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, HEAD';
add_header Referrer-Policy "no-referrer";
add_header Pragma "no-cache";
##################################
这在 Chrome 84 之前一直有效,但是,随着 Chrome 85 的最新更新,它开始抛出 CORS 错误,如下所示:
########## Chrome 85 中开始出现错误############
CORS 政策已阻止从源“https://mail.google.com”获取“https://my-site.com/”的访问权限:没有“Access-Control-Allow-Origin”标头存在于请求的资源上。
##########################################
在此之后,我根据来自各种来源和博客的建议/参考将 CORS 设置更新为全开放,现在更新后的 CORS 设置如下所示:
Nginx 中更新的 CORS 设置
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8' always;
add_header 'Content-Length' 0 always;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
}
}
###########################################
在 Nginx 中更新此设置后,CORS 错误消失了,但现在我在扩展程序调用 API 时从服务器收到 401 Unauthorized 错误。
我尝试调整所有方法,但无法修复它。有什么我遗漏或做不同的事情吗?
请帮忙!
【问题讨论】:
标签: google-chrome nginx cors passenger-nginx