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