Nginx跨域设置
参考:https://www.cnblogs.com/bninp/p/5694277.html
当出现403跨域错误的时候 No 'Access-Control-Allow-Origin' header is present on the requested resource
,需要给Nginx服务器配置响应的header参数:
在Nginx配置的location下添加以下配置
1 2 3 4 5 | add_header Access - Control - Allow - Origin * ; add_header Access - Control - Allow - Methods 'GET, POST, OPTIONS' ; add_header Access - Control - Allow - Credentials: true; add_header Access - Control - Allow - Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' ; |
PS:1,Access-Control-Allow-Origin允许跨域的源 * 代表允许所有,可以使用"http://域名"配置
2,需要在最终的目的Nginx配置,而不能在反向代理的Nginx配置
2024-10-14补充开始
设置跨域后在前端请求不生效返回405 nginx日志信息如下
1 | { "time_local" : "14/Oct/2024:15:17:35 +0800" , "remote_addr" : "1.1.1.1" , "request_uri" : "/v1/chat/completions" , "request_length" : "545" , "request_time" : "0.001" , "request_method" : "OPTIONS" , "status" : "405" , "body_bytes_sent" : "31" , "http_referer" : "https://wb-baidu.cloud.com/" , "http_user_agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36" , "http_x_forwarded_for" : "" , "http_host" : "edu.cloud.com" , "server_name" : "edu.cloud.com" , "upstream" : "192.168.3.26:8004" , "upstream_response_time" : "0.002" , "upstream_status" : "405" , } |
发现从前端发过来的请求方法是OPTIONS而不是POST
解决方法
修改配置文件在location增加以下配置加一个判断
1 2 3 4 5 6 7 | if ($request_method = OPTIONS ) { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' '*' ; add_header 'Access-Control-Allow-Headers' '*' ; add_header 'Access-Control-Allow-Credentials' 'true' ; return 200; } |
整体配置如下
2024-10-14补充结束
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!