1、什么是网站跨域
跨域原因产生:在当前域名请求网站中,默认不允许通过ajax请求发送其他域名。
2、网站跨域报错案例
jquery-1.7.2.min.js?t=2017-07-27:4 Failed to load http://b.itmayiedu.com:8081/ajaxB: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://a.itmayiedu.com:8080' is therefore not allowed access.
3、五种网站跨域解决方案
- 使用jsonp解决网站跨域 (不推荐, 因为只能支持get请求 不支持post请求)
- 使用HttpClient进行内部转发 (不推荐, 因为效率非常低,而且会发送两次请求,但是可以隐藏真实的请求地址)
- 使用设置响应头允许跨域(小项目这样做是推荐的)
- 基于Nginx搭建企业级API接口网关 (推荐,可以保证域名和端口一致,可以通过反向代理到真实服务器地址)
- 使用Zuul搭建微服务API接口网关(推荐)
4、具体方案实现
1、jsonp
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "GET",
async : false,
url : "http://b.com:8081/ajaxB",
dataType : "jsonp",
jsonp : "jsonpCallback",//服务端用于接收callback调用的function名的参数
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
@RequestMapping(value = "/ajaxB", method = RequestMethod.GET)
public void ajaxB(HttpServletResponse response, String jsonpCallback) throws IOException {
//下面这行代码放入到拦截器里面就好了,这里为了演示 就直接这里加了
response.setHeader("Content-type", "text/html;charset=UTF-8");
JSONObject root = new JSONObject();
root.put("errorCode", "200");
root.put("errorMsg", "登陆成功");
PrintWriter writer = response.getWriter();
writer.print(jsonpCallback + "(" + root.toString() + ")");
writer.close();
}
2、HttpClient
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "POST",
async : false,
url : "http://a.com:8080/forwardB",
dataType : "json",
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
先到A项目controller 然后A项目内部通过HttpClient转到B项目
A项目进行转发到B项目
@RequestMapping("/forwardB")
@ResponseBody
public JSONObject forwardB() {
JSONObject result = HttpClientUtils.httpGet("http://b.com:8081/ajaxB");
System.out.println("result:" + result);
return result;
}
B项目代码
@RequestMapping("/ajaxB")
public Map<String, Object> ajaxB(HttpServletResponse response) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("errorCode", "200");
result.put("errorMsg", "登陆成功");
return result;
}
3、设置响应头
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "GET",
async : false,
url : "http://b.com:8081/ajaxB",
dataType : "json",
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
@RequestMapping("/ajaxB")
public Map<String, Object> ajaxB(HttpServletResponse response) {
//项目中下面一代码放入到过滤器中,这里进行演示 就直接这里写了
response.setHeader("Access-Control-Allow-Origin", "*");
Map<String, Object> result = new HashMap<String, Object>();
result.put("errorCode", "200");
result.put("errorMsg", "登陆成功");
return result;
}
4、 基于Nginx搭建企业级API接口网关
nginx.conf 文件
server {
listen 80;
server_name www.test.com;
###A项目
location /a {
proxy_pass http://a.com:8080/;
index index.html index.htm;
}
###B项目
location /b {
proxy_pass http://b.com:8081/;
index index.html index.htm;
}
}
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type : "POST",
async : false,
url : "http://www.test.com/b/ajaxB",
dataType : "json",
success : function(data) {
alert(data["errorCode"]);
},
error : function() {
alert('fail');
}
});
});
</script>
@RequestMapping("/ajaxB")
public Map<String, Object> ajaxB(HttpServletResponse response) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("errorCode", "200");
result.put("errorMsg", "登陆成功");
return result;
}
5、使用SpringCloud Zuul搭建API接口网关 比较麻烦,需要搭建注册中心,一个A项目 一个B项目,还有一个网关,然后再网关项目的yml文件中配置如下
zuul:
routes:
api-a:
path: /api-a/**
serviceId: a
api-b:
path: /api-b/**
serviceId: b