【跨域】jsonp的实现

1.跨域是浏览器是浏览器的安全策略。协议、域名、端口号不同都会引起跨域。

2.html标签的src属性可以发起http请求,并不受跨域限制

 

服务端代码

服务端返回一段js执行代码,例如 func(data)。这段代码会在客户端执行

const http = require('http');
const urllib = require('url');

const data = [
  { name: 'zhangsan', age: 18 },
  { name: 'lisi', age: 18 },
  { name: 'wangwu', age: 18 },
];
const port = 3000;

http.createServer(function (req, res) {
  const urlParse = new urllib.URL(req.url, `http://127.0.0.1:${port}/`);
  const { searchParams } = urlParse;
  const callback = searchParams.get('callback');
  const name = searchParams.get('name');
  if (callback) {
    const hit = data.find(x => x.name === name);
    const result = `${callback}(${JSON.stringify(hit)})`;
    res.end(result);
  }
}).listen(port);

console.log(`Server running at http://127.0.0.1:${port}/`);

 

客户端代码

1.新建window.callback函数,直接返回数据;

2.新建script标签,将callback函数名和请求参数拼到url中,作为src的值;

3.将script元素放到body中,自动发起http请求,返回一段执行callback函数的js代码;

4.执行window.callback,返回数据;

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  
</head>
<body>
  
</body>
<script>
  function getJsonP(url, params) {
    return new Promise((resolve, reject) => {
      const callbackKey = `callback_${Date.now()}`;
      const ele = document.createElement('script');
      const query = Object.keys(params).reduce((pre, curr) => {
        return `${pre}&${curr}=${params[curr]}`;
      }, '');
      ele.src = `${url}${url.indexOf('?') === -1 ? '?' : '&'}callback=${callbackKey}${query}`;
      window[callbackKey] = (data) => {
        delete window[callbackKey];
        resolve(data);
        document.body.removeChild(ele);
      };
      document.body.append(ele);
    });
  };
  getJsonP('http://localhost:3000/?name=zhangsan', { name: 'zhangsan' }).then(data => {
    console.log(data);
  });
</script>
</html>

 

posted @ 2021-11-08 14:46  zhoulixue  阅读(102)  评论(0编辑  收藏  举报