Nginx反向代理配置可跨域

由于业务需要,同一项目中的前端代码放在静态环境中,而后端代码放在tomcat中,但此时问题却出现了:前端使用ajax请求后端获取数据时出现如下报错

1 XMLHttpRequest cannot load http://b.domain.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://a.domain.com' is therefore not allowed access.

经过多方面搜罗,找到以下解决方案:

在b.domain.com(即被请求域名)的Nginx反向代理配置文件的Server{}中加入如下配置:

1 add_header 'Access-Control-Allow-Origin' '*'; #允许的来源,为*时为所有,也可以设置为a.domain.com
2 add_header 'Access-Control-Allow-Headers' 'Content-Type,Origin,Accept';#指定将发送的实际请求标头
3 add_header 'Access-Control-Allow-Methods' 'HEAD,GET,POST,PUT,DELETE,OPTIONS';#指定实际请求的方法
4 add_header 'Access-Control-Max-Age' '120';#允许用户代理缓存预检请求以用于将来的请求的时间长度
原文地址:https://www.cnblogs.com/fanelephant/p/4228929.html