EC2生产环境部署应用遭遇CORS跨域问题求助
EC2部署应用时的CORS跨域问题
后端(BE)配置
app = FastAPI(title="App", openapi_url="/openapi.json") origins = ['http://localhost'] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"] )
前端(FE)请求代码
axios.get('http://localhost:8000/search/?' + searchQuery) .then((res) => { setData(JSON.parse(res.data)); });
Nginx配置
server { listen 80; location / { root /usr/share/nginx/html/; include /etc/nginx/mime.types; try_files $uri $uri/ /index.html; } }
问题现象
本地运行生产版本一切正常,但在EC2上通过axios请求数据时出现CORS错误:
- Chrome:
Cross-Origin Resource Sharing error: InsecurePrivateNetwork - Firefox:
CORS Missing Allow Origin
已尝试设置origins=["*"]但未解决问题,疑问:是否需要配置Nginx代理,让EC2公网IP发起的请求以localhost身份发送?
解决方案
1. 修正前端请求地址
EC2上的前端页面通过公网IP/域名访问时,前端代码写http://localhost:8000会触发浏览器安全限制——公网域请求本地私有网络,导致InsecurePrivateNetwork错误。
直接将请求地址改为EC2公网IP/域名+后端端口:
axios.get('http://你的EC2公网IP:8000/search/?' + searchQuery) .then((res) => { setData(JSON.parse(res.data)); });
2. 调整FastAPI的CORS配置
当allow_credentials=True时,allow_origins不能设为["*"](CORS规范强制要求),需将EC2公网IP/域名加入允许列表:
origins = [ "http://localhost", "http://你的EC2公网IP", # 若使用域名,添加:"http://your-domain.com" ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"] )
3. 配置Nginx反向代理(最优方案)
通过Nginx代理后端请求,统一访问域名/IP,彻底规避跨域问题:
修改Nginx配置,新增代理后端接口的location:
server { listen 80; # 前端静态文件路由 location / { root /usr/share/nginx/html/; include /etc/nginx/mime.types; try_files $uri $uri/ /index.html; } # 代理后端API请求 location /api/ { proxy_pass http://localhost:8000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
修改前端请求为相对路径:
axios.get('/api/search/?' + searchQuery) .then((res) => { setData(JSON.parse(res.data)); });
此时前端与后端请求均通过EC2公网IP/域名的80端口访问,属于同域,不会触发CORS校验。
内容的提问来源于stack exchange,提问作者Ironwing
相关产品推荐
相关产品推荐

