Nginx配置跨域(CORS)
由于浏览器同源策略导致Web应用访问其他站点资源时出现跨域问题。如下图
简单说下项目的现状:
1、服务端,Undertow嵌入式web服务器;
2、前端,通过Nginx托管;
Nginx跨域配置:
1、下载Nginx并安装。
2、打开Nginx根目录,config,找到 nginx.cnf 文件,新增如下配置:
server {
listen 80;
server_name localhost 127.0.0.1;
location / {
root c:\root\www\dist;
index index.html index.htm;
# 解决Vue3 history 模式报404问题,Vue2可忽略
try_files $uri $uri/ /index.html;
}
location /api {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_pass http://127.0.0.1:8010;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
}
特别说明:
(1)/api,表示监听所有“/api”开头的请求,比如后台接口:http://example.com/api/news/search?page=1&size=50。
(2)关于端口,80是前台页面的端口、8010是服务端api端口。
3、测试,已经能够正常返回数据!
本文来自博客园,作者:七月的枫丶 ,部分内容摘自互联网,转载请注明原文链接:https://www.cnblogs.com/easybook/p/16053926.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· 2分钟学会 DeepSeek API,竟然比官方更好用!
· .NET 使用 DeepSeek R1 开发智能 AI 客户端
· DeepSeek本地性能调优
· 一文掌握DeepSeek本地部署+Page Assist浏览器插件+C#接口调用+局域网访问!全攻略