跨域請求
http://www.xxx.com:8080/
協議號(http://)、子域名(www)、主域名(xxx)、端口號(8080)任何一處不同都算不同的域。
處理方法
1、代理
利用nginx做反向代理。配置如下
location /smarthome{
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET';
proxy_pass http://localhost:8082/com.anjubao.smarthome/;
}
add_header Access-Control-Allow-Origin 指定允許的url;
配置允許任何源跨域請求 http://localhost:8082/com.anjubao.smarthome/
2、springmvc配置
<!--springmvc restful跨域資源共享配置 -->
<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="*"
allowed-methods="GET, PUT, POST "
allowed-headers="Content-Type,X-Token,X-Username,accept, x-requested-with"
exposed-headers="" allow-credentials="false"
max-age="3600" />
</mvc:cors>
3、JSONP
服務器返回jsonp的格式的數據。
ajax請求如下:
$.ajax({
url : "http://10.10.121.40:9000/concurrency/default,
dataType:"jsonp",
jsonp:"callback",//回調函數
success: function (json) {
...
}
});
服務器代碼如下:
public static String toJSONPString(Object o){
if(o!=null){
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String callback = request.getParameter("callback");
String jsonString=JSON.toJSONString(o);
//jsonp數據返回格式:傳遞過來的回調函數名+(json數據)
String jsonpString=callback+"("+jsonString+")";
return jsonpString;
}else {
return "";
}
}
4、只需要在服務器端頭部加上下面兩句代碼:
header( "Access-Control-Allow-Origin:*" );
header( "Access-Control-Allow-Methods:POST,GET" );