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
  • 相关阅读:
    Django 登录页面重定向
    python 调试命令
    错误
    错误
    图算法之图的创建
    Git 常用命令详解(三)
    Git 常用命令详解(二)
    如何提问
    项目常用jquery/easyui函数小结
    我是怎么发现并解决项目页面渲染效率问题的(IE调试工具探查器的使用)
  • 原文地址:https://www.cnblogs.com/jimz/p/7541775.html
Copyright © 2011-2022 走看看