zoukankan      html  css  js  c++  java
  • 【跨域】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>
  • 相关阅读:
    接口测试的一个正常取值的实例
    接口测试的常见问题
    多接口(增删改查接口)的组合测试流程
    深入理解Java面向对象三大特性 封装 继承 多态
    vue.js入门
    Java,vue.js,jsp for循环的写法
    js的重载
    js的函数作用域
    闭包是什么以及封闭包怎么产生的?
    Leetcode 234. Palindrome Linked List
  • 原文地址:https://www.cnblogs.com/zhoulixue/p/15524237.html
Copyright © 2011-2022 走看看