:D ...

CORS跨域访问资源问题

什么是CORS CORS 遇到CORS问题 浏览器访问博客时,Giscus不显示,F12打开调试界面看到的Giscus资源链接访问返回了403,提示信息的意思是“缺少Access-Control-Allow-Origin"字段,这是跨域访问CORS限制问题,我们只需要增加"Access-Control-Allow-Origin"头信息到Nginx配置中,这样在访问 位于“https://img.shields.io/github/watchers/hexojs/hexo?style=social&label=watchers”的资源因其 Cross-Origin-Resource-Policy 头内容(或缺少该头)而被拦截。详见 https://developer.mozilla.org/docs/Web/HTTP/Cross-Origin_Resource_Policy_(CORP)#在/static目录下创建headers.toml文件,内容如下: toml 1 2 3 4 5 6 # custom header fields ["*"] cache-control = "max-age=3600" referrer-policy = "no-referrer" strict-transport-security = "max-age=31536000; includeSubDomains" Access-Control-Allow-Origin: * 重新生成站点文件,问题解决。 本站使用Nginx作为服务端,只需要在配置中添加如下配置头: nginx 1 add_header Access-Control-Allow-Origin *; 重新加载Nginx : systemctl reload nginx ,CORS问题解决了。 参考启用CORS配置如下: nginx 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 # # Wide-open CORS config for nginx # location / { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; # # 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'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } } 内容安全策略CSP(Content-Security-Policy) 内容安全策略通过 HTTP 响应标头传递,与HSTS非常相似,并定义了浏览器只加载的已批准内容源。SCP可以有效防止跨站点脚本 (XSS) 攻击,并且得到广泛支持并且通常易于部署。...

2024-01-15 周一 14:42:48 ·  阅读 2 分钟 ·  共 261 字 · 根叔