
1、跨文档通信 API:window.postMessage()
调用postMessage方法实现父窗口 A.com 向子窗口 B.com 发消息(子窗口同样可以通过该方法发送消息给父窗口。主要解决以下几种场景
页面和其打开的新窗口的数据传递
多窗口之间消息传递
页面与嵌套的iframe消息传递
上面三个场景的跨域数据传递
// 父窗口打开一个子窗口
var openWindow = window.open('https://ipkd.cn', 'hello');
// 父窗口向子窗口发消息(第一个参数代表发送的内容,第二个参数代表接收消息窗口的url)
openWindow.postMessage('how are you', 'https://ipkd.cn');
2、JSONP
JSONP 是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,兼容性好(兼容低版本IE),缺点是只支持get请求,不支持post请求。
核心思想:网页通过添加一个
⑴、JQ的方式
$.ajax({
url: 'https://ipkd.cn/login',
type: 'get',
data: {},
xhrFields: {
withCredentials: true // 前端设置是否带cookie
},
crossDomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie
});
⑵、原生js引入的方式
var xhr = new XMLHttpRequest();
// 前端设置是否带cookie
xhr.withCredentials = true;
xhr.open('post', 'https://ipkd.cn/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://ipkd.cn; #线上后台api
#proxy_pass https://ipkd.cn; #测试后台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://ipkd.cn',
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://ipkd.cn',
changeOrigin: true,
pathRewrite: {
'^/yunpos': '', // rewrite path
},
}));
app.listen(8081)
上面是“如何解决跨域”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_1507.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

宝塔面板部署Vue项目刷新页面404问题及解决
必应AI翻译:微软推出的一款支持70多种不同语言的免费翻译