关于javascript:老生常谈之跨域

2次阅读

共计 1519 个字符,预计需要花费 4 分钟才能阅读完成。

一、JSONP

  • <script src=""></script>

基本原理就是通过动态创建 script 标签,而后利用 src 属性进行跨域 (后端用回调函数名称包裹数据进行返回即可),然而要留神 JSONP 只反对 GET 申请,不反对 POST 申请:

// 回调函数
function showData (result) {
    // json 对象转成字符串
    $('#text').val(JSON.stringify(result));
}
$(document).ready(function () {$('#btn').click(function () {
        // 向头部输出一个脚本,该脚本发动一个跨域申请
        $('head').append('<script src="http://localhost:9090/student?callback=showData"><\/script>');
    });
});
  • jQueryJSONP 申请
$(document).ready(function () {$('#btn').click(function () {
        $.ajax({
            url: 'http://localhost:9090/student',
            type: 'GET',
            dataType: 'jsonp', // 指定服务器返回的数据类型
            jsonpCallback: 'showData',  // 也能够指定回调函数
            success: function (data) {
                // json 对象转成字符串
                $('#text').val(JSON.stringify(data));
            }
        });
    });
});

二、CORS 跨域资源共享

利用 nginx 或者 phpjava 等后端语言设置容许跨域申请:

header('Access-Control-Allow-Origin: *'); // 容许所有起源拜访
header('Access-Control-Allow-Method: POST,GET'); // 容许拜访的形式 

三、服务器代理

浏览器有跨域限度,然而服务器不存在跨域问题,所以能够由服务器申请所要域的资源再返回给客户端。

  • Nodejs 做代理 (eggjs)
async demo() {const { ctx: {inputs} } = this;
    const params = {
        ...inputs,
        token: '6f94a4917d57442c838f8476978ac475'
    };
    // 第三方接口地址
    const url = 'http://api.map.baidu.com/location/ip';
    // 获取第三方接口
    const data = await this.ctx.curl(url, {
        method: 'POST',
        dataType: 'text',
        timeout: 10000,
        data: params
    });
    // 返回数据
    this.success({data: data.data});
}

四、Nginx 反向代理

在配置文件 nginx.conf 中增加以下配置:

location / {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

    if ($request_method = 'OPTIONS') {return 204;}
}

更多文章

  • Github
  • 思否
  • 掘金
正文完
 0