如何解决跨域

2024年08月01日 建站教程

1、跨文档通信 API:window.postMessage()

调用postMessage方法实现父窗口 A.com 向子窗口 B.com 发消息(子窗口同样可以通过该方法发送消息给父窗口。主要解决以下几种场景
页面和其打开的新窗口的数据传递
多窗口之间消息传递
页面与嵌套的iframe消息传递
上面三个场景的跨域数据传递

// 父窗口打开一个子窗口
var openWindow = window.open('https://lmcjl.com', 'hello');
 
// 父窗口向子窗口发消息(第一个参数代表发送的内容,第二个参数代表接收消息窗口的url)
openWindow.postMessage('how are you', 'https://lmcjl.com');

2、JSONP

JSONP 是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,兼容性好(兼容低版本IE),缺点是只支持get请求,不支持post请求。

核心思想:网页通过添加一个

⑴、JQ的方式

$.ajax({
   url: 'https://lmcjl.com/login',
   type: 'get',
   data: {},
   xhrFields: {
       withCredentials: true    // 前端设置是否带cookie
   },
   crossDomain: true,   // 会让请求头中包含跨域的额外信息,但不会含cookie
});

⑵、原生js引入的方式

var xhr = new XMLHttpRequest(); 
 
// 前端设置是否带cookie
xhr.withCredentials = true;
 
xhr.open('post', 'https://lmcjl.com/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
 
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
};

3、Nginx(反向代理)

Nginx处理跨域的方式其实就是反向反向代理。那什么是反向代理呢?通俗一点说就是我们不能直接访问到目标服务器,这个时候我们就需要通过代理的方式实现,这种对于用户还是我们开发来说都是无感的,因为这些处理都是nginx帮我们处理好了。配置代码如下

listen       8081;
server_name  localhost 127.0.0.1;  //当前服务的域名


#location ~ ^/(yunpos|agent)/ {   //添加访问目录为/apis的代理配置
		#proxy_pass  https://lmcjl.com;  #线上后台api
		#proxy_pass  https://lmcjl.com;  #测试后台api
#}

4、Node服务端代理

⑴、koa-server-http-proxy是koa2的中间件

const Koa = require('koa')

const app = new Koa()

const proxy = require('koa-server-http-proxy')

app.use(async (ctx, next)=> {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (ctx.method == 'OPTIONS') {
    ctx.body = 200;
  } else {
    await next();
  }
});


app.use(proxy('/yunpos', {
  target: 'https://lmcjl.com',
  pathRewrite: { '^/yunpos': '' },
  changeOrigin: true
}))

app.listen(8081)

⑵、http-proxy-middleware是node.js提供的代理方式

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

app.use('/yunpos',
  createProxyMiddleware({
    target: 'https://lmcjl.com',
    changeOrigin: true,
    pathRewrite: {
    '^/yunpos': '', // rewrite path
  },
  }));
app.listen(8081)

本文链接:http://so.lmcjl.com/news/9685/

展开阅读全文
相关内容