`

html5跨域方法

 
阅读更多

从html5开始,可以通过在响应头里增加Access-Control-Allow-Origin,实现跨域请求

node的代码:

 

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Authorization,Origin, Accept, Content-Type, X-HTTP-Method, X-HTTP-METHOD-OVERRIDE,XRequestedWith,X-Requested-With,xhr,x-devicetype');


当然,生产环境里不能把Allow-Origin设置成*,而应该设置成允许跨域访问的源站的域名。Allow-Headers是允许跨域请求携带的http request header

客户端的代码:

 

$.ajax({
                    type: 'POST',
                    url: url,
                    data: {
                        content: content
                    },
                    beforeSend: function(request) {
                        request.setRequestHeader("x-wxopenid", hash);
                        request.setRequestHeader("x-devicetype", deviceType);
                    },
                    xhrFields:{
                        withCredentials: true
                    },
                    crossDomain: true,
                    success: function(data){
                        showTipsThenClose();
                    },
                    error: function(err){
                        showTipsThenClose();
                    },
                    dataType:"json"
                });



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics