什么是跨域
不同協議 不同域名 不同子域 不同端口 均為跨域
特別的:一個域名和其對應的ip地址也算跨域
具體見下表
跨域請求無效
默認情況下,比如在localhost:63342下使用ajax請求localhost:8800
$.get("http://localhost:8080/api/getProducts")
會發生錯誤:
XMLHttpRequest cannot load http://www.baidu.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
解決方案
只介紹一種解決方案
在http Response header中加入“Access-Control-Allow-Origin”字段,其值設置為發起請求的域名;或者*,表示所有域名都可以跨域對此域名進行訪問
函數參數中加入HttpServletResponse
調用其setHeader函數,在header中加入相應字段
代碼如下
@ResponseBody
@RequestMapping(value={"api/getproducts.json"})
public String getProducts(HttpServletResponse responce){
responce.setHeader("Access-Control-Allow-Origin","*");
return JSON.toJSONString(productService.findAllProducts());
}
還有其他解決方案,比如使用jsonp,在此不做介紹