ajax跨域资源请求解决

跨域请求

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" );


 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值