zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    让数据更精准,神器标配:热图
    运维监控大数据的提取与分析
    IT运营新世界大会:广通软件开启双态运维大时代
    持续交付的Mesos与Docker导入篇
    运算符
    Django 模型层(2)
    Django模型层
    Django的模板层
    Django的视图层
    Django的路由层(URLconf)
  • 原文地址:https://www.cnblogs.com/jimz/p/7541775.html
Copyright © 2011-2022 走看看