Ajax跨域 CROS处理

Ajax跨域方法有多种 这里介绍CROS跨域的实际案例

场景:A域名 请求 B域名;

暂且 A为客户端 B为服务端;

请求的服务端必须自己能控制 或者服务器端头部已经添加 Access-Control-Allow-Origin :允许你 的域名

服务端:

header("Access-Control-Allow-Origin:http://www.xxxx.com"); 
header("Access-Control-Allow-Method:POST,GET,OPTIONS"); 
header("Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept"); 
header('Access-Control-Allow-Credentials: true');
Access-Control-Allow-Origin 未允许跨域请求的ip或地址
Access-Control-Allow-Method 请求方式
Access-Control-Allow-Headers 支持的头信息字
Access-Control-Allow-Credentials 要想发送Cookie 这个配置必须为true

服务端实现以上配置,客户端基本上可以跨域请求了

客户端:
$.ajax({
                url: B域名, 
                dataType: 'json',
                data: {username:username,password: password},
                contentType: 'application/json; charset=utf-8',
                type: 'get',
                withCredentials: true,
                async:true,
                beforeSend: function(xhr) {
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    },
                xhrFields:{
                    withCredentials:true
                    },
                success: function(result){
                    console.log(result);
                    if(result.type == 'success'){
                        window.location.href='http://we.lb.com/web/'+result.redirect;
                    }
                }, 
                error: function(error){
                    console.log(error);
                },
            });
                beforeSend: function(xhr) {
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    },

这个设置是请求头部信息
X-Requested-With:XMLHttpRequest,在我的项目里没添加这个 服务端识别不了ajax请求;若能识别忽悠就可以
                xhrFields:{
                    withCredentials:true
                    },

这个设置
withCredentials:true, 如果发送Cookie 这个配置必须要有;

参照:http://www.ruanyifeng.com/blog/2016/04/cors.html
posted @ 2017-09-18 10:16  百事可口  阅读(404)  评论(0编辑  收藏  举报