前端解决跨域的几种方式

为了简单验证跨域方法,通过 koa2 创建一个项目模拟后端接口,并在该项目下新建 html 文件,并通过 iframe 访问 koa 服务,以此实现跨域情况。

1、 iframe + postMessage方式

postMessage方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。

语法:

otherwindow.postMessage(message, targetOrigin, [transfer]);

  • otherwindow:其他窗口的引用;
  • message:将要发送到其他window的数据;
  • targetOrigin:指定那些窗口能接收到消息事件,其值可以是字符串“*” 表示无限制,或者是一个URI;
  • transfer:是一串和message同时传递的Transferable对象,这些对象的 所有权将被转移给消息的接收方,而发送方将不再保留所有权。

index.html内容如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <h1>window</h1>
    <iframe src="http://localhost:3000/" id="iframe"></iframe
    <script src="./axios.min.js"></script>
    <script>
      window.onload = function() {
        const iframe = document.querySelector("#iframe");
        // 模拟 get 请求
        iframe.contentwindow.postMessage({
          type: "GET",
          url:"/getMessage",
          data:{
            a: 1,
            b: 2
        }, "http://localhost:3000/");

        // 模拟 post 请求
        iframe.contentwindow.postMessage({
          type: "POST",
          url: "/postMessage",
          data: {
            a:1,
            b: 2
        }, "http://localhost:3000/");

       // 监听 iframe 中的回调
       window.addEventlistener("message", (event) => {
         console.log("parent:", event.data);
       },false);
    </script>
  </body>
</html>

koa 页面监听到 message事件后,发起ajax请求;首页index.pug内容如下:

// views/index.pug

block content
script(src="/javascripts/jquery.js")
script.
 window.addEventListener("message", (event) => {
  // current window object
  //- console.log(window);
  // parent window object
  //- console.log(event.source);
  if (window.parent !== event.source) return;
  const options = event.data;
  console.log('iframe:', options);
  $.ajax({
    type: options.type || "GET",
    url: options.url,
    dataType: options.datatype || "json",
    data: options.data || {},
    success: function(res) {
      top.postMessage(res, "file:///D:/koa-cors/index.html");
    },
    error: function(err){
      top.postMessage(err, "file:///D:/koa-cors/index.html");
    }
  })
 },false);

koa接口处理请求

// routes/index.js
//GET methods
router.get('/getMessage', async (ctx, next) => {
  console.log(ctx.querystring);
  const query = ctx.query;
  ctx.body = query;
  ctx.status = 200;
});

// POST methods
router.post('/postMessage', async (ctx, next) => {
  console.log(ctx.request.body);
  const body = ctx.request.body;
  ctx.body = body;
  ctx.status = 200;
});

2、jsonp方式

基本原理:

主要就是利用了script标签的src没有跨域限制来完成的。

优缺点:
  • 缺点:只能执行get请求
  • 优点:兼容性好,在一些古老的浏览器中也能执行

index.html内容如下:

function jsonp(url, data = {}) {
  return new Promise((resolve, reject) => {
    jsonp.index = jsonp.index + 1 || 0;  
    const fn =  `__fn__${jsonp.index}`;
    jsonp[fn] = data => {
      resolve (data)
      delete jsonp[fn]
    };
    let script = document.createElement("script");
    let query= object.entries(data).map(a=> ${a[0]}=${a[1]}).join("&");
    script.src = `${url}?callback=jsonp.${fn}&${query}`;
    script.onerror = () => reject("failed");
    document.head.appendChild(script);
    document.head.removeChild(script);
});

jsonp('http://localhost:3000/jsonp', {city: "北京"}).then(data => {
  console.log('a:', data)
}).catch(e => console.log(e));

jsonp ('http://localhost:3000/jsonp', {city: "深圳"}).then(data => {
  console.log('b:', data)
}).catch(e => console.log(e));

jsonp('http://localhost:3000/jsonp', {city: "上海"}).then(data => {
  console.log('c:', data)
}).catch(e => console.log(e));

koa接收请求后,取出url中的入参,尤其是把callback的名称拿到,再通过该名称包裹返回数据,如:callback(data)即可

// routes/index.js
router.get('/jsonp',  async (ctx, next) => {
  const query = ctx.query;
  ctx.body = `${query.callback}({city: "${query.city}"})`;
  ctx.status = 200;
})

3、cors方式

全称"跨域资源共享"
CORS需要浏览器和服务器同时支持,才可以实现跨域请求,目前几乎所有浏览器都支持CORS,IE则不能低于IE10。CORS的整个过程都由浏览器自动完成,前端无需做任何设置,跟平时发送aiax请求并无差异。

请求类型:
  • 简单请求:浏览器会直接发送CORS请求,具体说来就是在header中加入 origin请求头字段。
    符合一下条件为简单请求:
  请求方式:GET、HEAD、POST
  Content-type: text/plain、multipart/form-date、application/x-www-form-urlencoded
  • 非简单请求:当发生符合非简单请求(预检请求)的条件时,浏览器会自 动先发送一个options请求,如果发现服务器支持该请求,则会将真正的 请求发送到后端,反之,如果浏览器发现服务端并不支持该请求。

非简单请求如下:

const instance = axios.create({
  baseURL: "http://localhost:3000", 
  // 模拟自定义请求头
  headers: {
    TIME: new Date().getTime(), 
    TOKEN: 12345,
    "Content-Type": "application/json"
  }
});

// 模拟 post 请求
instance.post("/cors-post", data: {
  a: {a: 1,b: 2},
  b: [{a: 1, b: 2}, {a: 3, b: 4}]
}).then(res => {
  console.log(res);
});

// 模拟 get 请求
instance.get("/cors-get").then(res => {
  console.log(res);
});

在koa的lib文件夹下新建koa-cors,js文件,通过中间件的形式在业务接口处理前,设置跨域请求信息

module.exports = async (ctx, next) => {
  //必须,允许访问的域名(*或具体域名),开发阶段后端可能是具体域名而前端是 http://localhost:[port],要沟通清楚否则会导致联调失败
  ctx.set("Access-Control-Allow-origin", "*");
  //必须,允许访问的请求方式(*或具体方法类型)
  ctx.set("Access-Control-Allow-Methods", "OPTIONS, POST, GET, PUT, DELETE");
  //选填,允许请求头携带的字段,根据前端传过来的字段设置,前后端不匹配会导致请求失败
  ctx.set("Access-Control-Allow-Headers". "TIME, TOKEN, accept, origin, content-type");
  //选填,是否允许携带cookies,前端:withcredentials = true
  // ctx.set("Access-Control-Allow-Credentials", true)
  //选填,设置content-type类型
  // ctx.set("Content-Type", "application/x-www-form-urlencoded");

  console.log(ctx.request.body);
  if (ctx.method == "OPTIONS") {
    ctx.body = "";
    ctx.status = 204;
  } else {
    await next();
  }

在app.js中引入

const app = new Koa();
const cors = require("./libkoa-cors");
app.use(cors);

接口正常处理业务逻辑即可

// routes/index.js
// 相应 post 请求
router.post("/cors-post", async (ctx, next) => 
  ctx.body = {
    data: "cors-post"
  };
  ctx.status = 200;
});

// 相应 get 请求
router.get("/cors-get", async (ctx, next) => 
  ctx.body = {
    data: "cors-get"
  };
  ctx.status = 200;
});

4、fiddler抓包工具

匹配规则fiddler自动响应AutoResponder之正则匹配Rule Editor
前缀为"EXACT:"表示完全匹配(大小写敏感)
无前缀表示基本搜索,表示搜索到字符串就匹配
前缀为"REGEX:"表示使用正则表达式匹配
前缀为"REGEX:(?insx)"表示匹配方式其中:
表示不区分大小写;

  • n 表示指定的唯一有效的捕获是显式命名或编号的形式;
  • s 表示单行模式;
  • x 表示空格说明的;
  • 前缀为"NOT:"表示发现就不四配

常用修改接口设置代理,ruler editor如:

// 拦截 URL
regex:(?insx)^http://localhost:8080/api/(?<args>.*)$
// 重定向 URL
http://www.abc.cn/api/${args}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容