location /dyl-server/ {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;
add_header Access-Control-Allow-Headers phone,Referer,Origin,X-Requested-With,Content-Type,Accept,Authorization,uToken,orgId,rootOrgId,token,uid,uName;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Request-Method X-Requested-With,Content-Type,Accept,Platform,Token,Authorization;
add_header Access-Control-Max-Age 3601;
return 200;
}
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods *;
add_header Access-Control-Allow-Headers phone,Referer,Origin,X-Requested-With,Content-Type,Accept,Authorization,uToken,orgId,rootOrgId,token,uid,uName;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Request-Method X-Requested-With,Content-Type,Accept,Platform,Token,Authorization;
add_header Access-Control-Max-Age 3602;
proxy_pass http://yc-test/;
Nginx服务器可以通过添加跨域资源共享(CORS)头来解决跨域问题。在Nginx服务器上实现CORS,可以根据不同的项目或网站实际情况进行不同的配置,并且控制在服务端进行,提高了数据安全性。
以下是Nginx跨域实现的步骤:
找到nginx配置文件,默认位置为 /etc/nginx/nginx.conf。
在server段,添加如下代码:
Copy code
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Content-Type';
if ($request_method = 'OPTIONS') {
return 200;
}
}
重启nginx服务器。
以上代码中:
add_header 'Access-Control-Allow-Origin' '*':允许跨域访问的域名。其中,'*'表示允许所有域名访问。
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE':允许跨域访问的方法,如GET、POST、OPTIONS等。
add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Content-Type':允许跨域访问的请求头,如X-Requested-With、Content-Type等。
if ($request_method = 'OPTIONS') { return 200; }:判断请求方法是否为OPTIONS,如果是则返回200。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?