Access
如何解决Access-Control-Allow-Origin跨域问题前提环境:在A服务器,调用B服务器的资源,报错出现找不到请求头Access-Control-Allow-Origin,输入跨域问题, 需要使用配置nginx来处理
例如:A服务器是liunx系统部署了一个java程序,B服务器是本地服务器,A服务器需要请求访问B服务器的资源,可以用nginx代理来请求到B服务器的资源。
文章目录 如何解决Access-Control-Allow-Origin跨域问题配置nginx.conf文件一、如何配置你的nginx.conf二、添加Access-Control-Allow-Methods请求头 总结
配置nginx.conf文件
提示:先下载启动nginx,官网下载链接: nginx
步骤:下载完成后安装运行在A服务器上面,先运行看看有没有问题,这里不细说,然后找到开始配置nginx.conf文件(重点)
代码如下(示例):
server { listen 9800; server_name localhost; #后台接口配置 location ~ /quartz/ { proxy_pass http://192.168.X.XXX:9830;proxy_read_timeout 360s;proxy_send_timeout 360s;proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;add_header Front-End-Https on;add_header 'Access-Control-Allow-Methods' 'GET,POST';add_header 'Access-Control-Allow-Origin' $http_origin;add_header 'Access-Control-Allow-Credentials' 'true';add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';} }location / { root html; index index.html index.htm; }location @router { rewrite ^.*$ /index.html last; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }一、如何配置你的nginx.conf
添加一个server{},这是你的服务,listen参数是你要监听的端口,这个端口可以自定义,server_name localhost,这个一般就是A服务器的域名地址,记住这个地址+端口+/参数/(127.0.0.1:9800/quartz/) 是映射location,也就是请求的地址会被代理成 proxy_pass http://192.168.X.XXX:9830这个地址,A服务器就可以跨服务器请求B服务器的资源;
二、添加Access-Control-Allow-Methods请求头代码如下(示例):
add_header Front-End-Https on;add_header 'Access-Control-Allow-Methods' 'GET,POST';add_header 'Access-Control-Allow-Origin' $http_origin;add_header 'Access-Control-Allow-Credentials' 'true';add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';header头字段含义取值Access-Control-Allow-Credentials响应头表示是否可以将对请求的响应暴露给页面true/falseAccess-Control-Allow-Headers表示此次请求中可以使用那些header字段符合请求头规范的字符串Access-Control-Allow-Methods表示此次请求中可以使用那些请求方法GET/POST(多个使用逗号隔开)Access-Control-Allow-Origin一种跨域策略,标识的Response header,用来解决资源的跨域权限问题。标识符总结
提示:这里对文章进行总结:
以上就是今天要讲的内容,本文仅仅简单介绍了用nginx来解决Access-Control-Allow-Origin跨域问题;
Access-Control-Allow-Origin跨域问题,使用Nginx配置来解决