常用跨域

目录

  1. JSONP

正文

  • JSONP

优缺点:

JSONP优点是简单兼容性好,可用于解决主流浏览器的跨域数据访问的问题。缺点是仅支持get方法具有局限性,不安全可能会遭受XSS攻击。

实现原理:

  • 声明一个回调函数,其函数名(如show)当做参数值,要传递给跨域请求数据的服务器,函数形参为要获取目标数据(服务器返回的data)。
  • 创建一个<script>标签,把那个跨域的API数据接口地址,赋值给script的src,还要在这个地址中向服务器传递该函数名(可以通过问号传参:?callback=show)。
  • 服务器接收到请求后,需要进行特殊的处理:把传递进来的函数名和它需要给你的数据拼接成一个字符串,例如:传递进去的函数名是show,它准备好的数据是show(‘data’)。
  • 最后服务器把准备的数据通过HTTP协议返回给客户端,客户端再调用执行之前声明的回调函数(show),对返回的数据进行操作。
    代码:
    后端:
const http = require('http');
const url = require('url');
const PORT = 8889;

// 创建一个 http 服务
const server = http.createServer((request, response) => {
  // 获取前端请求数据
  const queryObj = url.parse(request.url, true).query;
  console.log(queryObj);
  // 这里把前端传来的 callback 字段作为后端返回的回调函数的函数名称
  response.end(`${queryObj.callback}({name: '后台返回的数据'})`);
});

server.listen(PORT, () => {
  console.log('服务启动成功!');
})

前端:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>JSONP</title>
</head>
<body>
  JSONP
</body>
<script>
  function Jsonp(url, cb) {
    this.callbackName = 'jsonp_' + Date.now();
    this.cb = cb
    this.url = url
    this.init()
}

// 初始化方法 用于拼接 url
Jsonp.prototype.init = function() {
    if(~this.url.indexOf('?')) {
        this.url = this.url + '&callback=' + this.callbackName
    } else {
        this.url = this.url + '?callback=' + this.callbackName
    }
    this.createCallback()
    this.createScript()
}

// 创建 script 标签, src 取接口请求的url
Jsonp.prototype.createScript = function() {
    var script = document.createElement('script')
    script.src = this.url
    var that = this;
    script.onload = function() {
        // 删除标签
        // document.body.removeChild(script);
        this.remove();
        
        // 删除 window 下定义的无用方法
        delete window[that.callbackName]
        console.log('that.callbackName: ', that.callbackName); 
    }
    document.body.appendChild(script)
}

// 绑定回调函数
Jsonp.prototype.createCallback = function() {
    window[this.callbackName] = this.cb
}

// 创建 jsonp 实例, 并指定回调函数
new Jsonp('http://localhost:8889/a', function(data) {
    console.log(data)
})

</script>
</html>

猜你喜欢

转载自blog.csdn.net/ky1in93/article/details/87601052