面试官问道:常见的跨域处理方式有哪些?
ztj100 2024-12-11 18:23 15 浏览 0 评论
作者:一川
1.写在前面
同域和跨域问题是老生常谈的问题,同源无外乎:主机、端口号、协议保持一致,当其中一个不一致的时候就是存在跨域问题,这时候就需要我们进行处理。
常见的跨域方案有以下九种:
- JSONP
- CORS
- postMessage
- webSocket
- window.name + iframe
- document.domain + iframe
- location.hash + iframe
- nginx反向代理
- http-proxy
2.JSONP
JSONP(JSON with Padding) 是JSON的一种‘使用模式’,可以跨域的获取到数据。
手写JSONP代码的思路是:
- 设置等待我们请求的url,将参数对象params的参数进行拼接得到一个字符串
- 构造script
- js代码使用document.createElement创建一个script标签
- 返回一个Promise,无论最终是返回成功还是失败的数据,都要对script标签进行移除
请求页面代码index.html:
<script>
function jsonp({url, params,cb}){
return new Promise((resolve,reject)=>{
params = {...params, cb} //wd=yichuan_i_love_you&cb=show
let arrs = [];
for(let key in params){
arrs.push(`${key}=${params[key]}`)
}
let script = document.createElement("script");
script.src = `${url}?${arrs.join("&")}`;
document.body.appendChild(script);
window[cb] = function(data){
try{
resolve(data)
}catch(e){
reject(e)
}finally{
// 最后要移除此标签
script.parentNode.removeChild(script);
}
}
})
}
// 只能发送get请求,不支持post put delete
// 不安全,容易被xss攻击
jsonp({
url:"http://localhost:3000/say",
params:{wd:"yichuan_i_love_you"},
cb:"show"
}).then(data=>{
console.log(data);
})
</script>
1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.
服务器代码:
const express = require("express")
const app = express()
app.get("/say",(req,res)=>{
const {wd, cb} = req.query;
console.log("wd", wd);
res.end(`${cb}("Pingping i love you")`)
})
app.listen(3000,()=>{
console.log(`this is server is running...`);
})1.2.3.4.5.6.7.8.9.10.11.12.
服务器打印:
页面数据打印:
我们看到当刘拉你去通过jsonp向后端请求时,后端接收请求后进行打印数据,而后向前端返回Pingping i love you在控制台进行打印。
3.CORS
我们知道JSONP也可以跨域,那为什么还要使用CORS呢?
- jsonp只可以使用 GET 方式提交
- 不好调试,在调用失败的时候不会返回任何状态码
- 安全性问题
当提供JSONP的服务被恶意注入漏洞,那么它返回数据的JS内容就被人控制了,这样调用这个JSONP的网站都会存在这个漏洞,因此必须在确保JSONP内容安全可靠的时候才能进行使用。
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing),他允许浏览器向跨源服务器发送XMLHttpRequest请求,从而克服啦 AJAX 只能同源使用的限制。
CORS需要浏览器和服务器同时支持,整个 CORS通信过程,都是浏览器自动完成不需要用户参与,对于开发者来说,CORS的代码和正常的 AJAX 没有什么差别,浏览器一旦发现跨域请求,就会添加一些附加的头信息。
但是,CORS仅支持IE10以上的版本。
index.html
<script>
const xhr = new XMLHttpRequest;
// true 开启异步
xhr.open("GET","http://localhost:3001/getData",true);
xhr.onreadystatechange = ()=>{
if(xhr.readyState === 4){
if(200 <= xhr.status && xhr.status < 300 || xhr.status === 304){
console.log(xhr.response);
}
}
}
xhr.send()
</script>1.2.3.4.5.6.7.8.9.10.11.12.13.
server01.js
const express = require("express");
const app = express();
app.use(express.static(__dirname));
app.listen(3002,()=>{
console.log(`http://localhost:3002`);
});1.2.3.4.5.6.
server02.js
复制const express = require("express")
const app = express()
app.get("/getData",(req,res)=>{
const {wd, cb} = req.query;
console.log("wd", wd);
res.end(`${cb}("Pingping i love you")`)
})
app.listen(3001,()=>{
console.log(`this is server is running...`);
})1.2.3.4.5.6.7.8.9.10.11.12.13.
我们看到,当写好了ajax请求代码,在启动server01.js服务后,在浏览器向后端请求数据,我们发现出现了跨域报错。
那么我们需要在后端服务进行设置Access-Control-Allow-Origin实现跨域请求。
复制const whitList = ["http://localhost:3002"]
app.use((req, res, next)=>{
const origin = req.headers.origin;
if(whitList.includes(origin)){
// 设置哪个源可以访问我们
res.setHeader("Access-Control-Allow-Origin",origin);
// 允许携带哪个头访问我
res.setHeader("Access-Control-Allow-Headers","name");
// 允许哪个方法访问我 默认允许get post请求
res.setHeader("Access-Control-Allow-Methods","PUT");
// 允许携带cookie
res.setHeader("Access-Control-Allow-Credentials",true);
// 预检的存活时间
res.setHeader("Access-Control-Max-Age",10);
// 允许返回的头
res.setHeader("Access-Control-Expose-Headers","name");
if(req.method === "OPTIONS"){
res.end();//OPTIONS请求不做任何处理
}
}
next()
})1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.
此时,我们看到:
4.postMessage
postMessage是H5引入的API,postMessage()方法允许来自不同源的脚本采用异步方式进行有效的通信,可以实现跨文本文档、多窗口、跨域消息传递。多用于窗口间数据通信,这也使它成为跨域通信的一种有效的解决方案。
发送数据:
otherWindow.postMessage(message, targetOrigin, [transfer]);1.
pingping.html
<h1>i love u onechuan</h1>
<script>
window.onmessage = (e)=>{
console.log(e.data);
e.source.postMessage("i love u too, onechuan", e.origin)
}
</script>1.2.3.4.5.6.7.
onechuan.html
<iframe src="http://localhost:3001/pingping.html"
frameborder="0" id="frame" onload="load()">
</iframe>
<script>
function load(){
const frame = document.getElementById("frame");
frame.contentWindow.postMessage("i love u pingping", "http://localhost:3001")
window.onmessage = (e)=>{
console.log(e.data);
}
}
</script>1.2.3.4.5.6.7.8.9.10.
我们可以看到,在onechuan.html中通过postMessage请求并展示了pingping.html页面的数据,控制台出现了i love u onechuan。
5.window.name+iframe
window.name属性name 值在不同的页面(甚至不同域名)加载后依旧存在(如果没修改则值不会变化),并且可以支持非常长的 name 值(2MB)。并且使用window.name很方便。
name 在浏览器环境中是一个全局/window对象的属性,且当在 iframe 中加载新页面(可以是不同域的)时,name 的属性值依旧保持不变(只要不重新赋值)。name属性的值虽然不变,但对它的访问还是受到同域原则,不允许访问。所以我们要把iframe重新定向回原域,这样name的值也没变,并且可以访问了。
- a.html和b.html是同域的 http://localhost:3000
- c.html 是独立的 http://localhost:3001
- a.html获取c.html的数据
- a.html先引用c.html,c把值放在window.name,把a引用的地址改为b.html
a.html
<iframe src="http://localhost:3001/c.html" frameborder="0" onload="load()" id="iframe">
</iframe>
<script>
let first = true;
// onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
function load(){
// 第1次onload(跨域页)成功后,切换到同域代理页面
if(first){
//加载完url后,重新定向回原域
let iframe = document.getElementById("iframe")
iframe.src = "http://localhost:3000/b.html";
first = false;
}else{
// 第2次onload(同域b.html页)成功后,读取同域window.name中数据
console.log(iframe.contentWindow.name);
}
}
</script>1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
b.html为中间代理页,与a.html同域,内容为空。
c.html
<h1>c</h1>
<script>
window.name = "ccc"
</script>
1.2.3.4.
总结:通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。
6.location.hash+iframe
实现原理:a.html欲与c.html跨域相互通信,通过中间页b.html来实现。三个页面,不同域之间利用iframe的location.hash传值,相同域之间直接js访问来通信。
路径后面的hash值可以用来通信,我们的目的从a想访问c,那么从a给c传一个hash值,c收到hash值后,c把hash值传递给b,那么b将结果放在a的hash值中。
a.html
<iframe src="http://localhost:3000/c.html#iloveu" frameborder="0"></iframe>
<script>
//检测hash的变化
window.onhashchange = ()=>{
console.log(location.hash);
}
</script>1.2.3.4.5.6.7.
b.html
<h1>b</h1>
<script>
//b.html将结果放到a.html的hash值中,b.html可通过parent.parent访问a.html页面
window.parent.parent.location.hash = location.hash
</script>
1.2.3.4.5.
c.html
<script>
console.log(location.hash);
const iframe = document.createElement("iframe");
iframe.src = "http://localhost:3000/b.html#iloveu";
document.body.appendChild(iframe);
</script>1.2.3.4.5.6.
在a.html页面通过iframe打开c.html页面,而c.html中创建iframe标签设置src为b.html,最终打开了b.html页面,能够在控制台打印hash值。
7.document.domain + iframe
该方式只能用于二级域名相同的情况下,比如 a.onechuan.com 和 b.onechuan.com 适用于该方式。只需要给页面添加 document.domain ='onechuan.com' 表示二级域名都相同就可以实现跨域。
实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域。我们看个例子:页面a.onechuna.com:3000/a.html获取页面b.onechuan.com:3000/b.html中a的值
a.html
<iframe src="http://b.onechuan.com:3001/b.html"
id="iframe" onload="load()" frameborder="0"
</iframe>
<script>
// 域名 一级域名 二级域名
// www.onechuan.com
// oc.onechuan.com
// a是通过http://oc.onechuan.com
const iframe = document.getElementById("iframe")
document.domain = "onechuan.com"
function load(){
console.log(iframe.contentWindow.b);
}
</script>1.2.3.4.5.6.7.8.9.10.11.12.
b.html
<script>
document.domain = "onechuan.com"
var b = 100;
</script>1.2.3.4.
设置host:
127.0.0.1 a.onechuan.com
127.0.0.1 b.onechuan.com1.2.
8.webSocket
WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。
实际使用的时候,我们会用封装好的Socket.io。
websocket.html
<script>
// 高级api 不兼容socket.io 一般使用它
let socket = new WebSocket("ws://localhost:3000")
socket.onopen = ()=>{
socket.send("i love u pingping")
}
socket.onmessage = (e)=>{
console.log(e.data);
}
</script>1.2.3.4.5.6.7.8.9.10.
server.js
const WebSocket = require("ws");
const wss = new WebSocket.Server({port:3000});
wss.on("connection",ws=>{
ws.on("message",data=>{
console.log("data",data);
ws.send("i love u onechuan")
})
})1.2.3.4.5.6.7.8.
9.nginx反向代理
使用nginx反向代理实现跨域,是最简单的跨域方式。只需要修改nginx的配置即可解决跨域问题,支持所有浏览器,支持session,不需要修改任何代码,并且不会影响服务器性能。
实现思路:通过nginx配置一个代理服务器(域名与domain1相同,端口不同)做跳板机,反向代理访问domain2接口,并且可以顺便修改cookie中domain信息,方便当前域cookie写入,实现跨域登录。
先下载nginx,然后将nginx目录下的nginx.conf修改如下:
复制// proxy服务器
server {
listen 81;
server_name www.domain1.com;
location / {
proxy_pass http://www.domain2.com:8080; #反向代理
proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名
index index.html index.htm;
# 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
add_header Access-Control-Allow-Origin http://www.domain1.com; #当前端只跨域不带cookie时,可为*
add_header Access-Control-Allow-Credentials true;
}
}1.2.3.4.5.6.7.8.9.10.11.12.13.14.
最后通过命令行nginx -s reload启动nginx。
index.html
复制var xhr = new XMLHttpRequest();
// 前端开关:浏览器是否读写cookie
xhr.withCredentials = true;
// 访问nginx中的代理服务器
xhr.open('get', 'http://www.domain1.com:81/?user=admin', true);
xhr.send();1.2.3.4.5.6.
server.js
复制var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request', function(req, res) {
var params = qs.parse(req.url.substring(2));
// 向前台写cookie
res.writeHead(200, {
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly:脚本无法读取
});
res.write(JSON.stringify(params));
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');1.2.3.4.5.6.7.8.9.10.11.12.13.14.
10.http-proxy
同源策略是浏览器需要遵循的标准,而如果是服务器向服务器请求就无需遵循同源策略。
代理服务器,需要做以下几个步骤:
- 接受客户端请求 。
- 将请求转发给服务器。
- 拿到服务器 响应 数据。
- 将 响应 转发给客户端。
我们先来看个例子:本地文件index.html文件,通过代理服务器http://localhost:3000向目标服务器http://localhost:4000请求数据。
// index.html(http://127.0.0.1:5500)
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
url: 'http://localhost:3000',
type: 'post',
data: { name: 'xiamen', password: '123456' },
contentType: 'application/json;charset=utf-8',
success: function(result) {
console.log(result) // {"title":"fontend","password":"123456"}
},
error: function(msg) {
console.log(msg)
}
})
</script>1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.
server.js
// server1.js 代理服务器(http://localhost:3000)
const http = require('http')
// 第一步:接受客户端请求
const server = http.createServer((request, response) => {
// 代理服务器,直接和浏览器直接交互,需要设置CORS 的首部字段
response.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': 'Content-Type'
})
// 第二步:将请求转发给服务器
const proxyRequest = http
.request(
{
host: '127.0.0.1',
port: 4000,
url: '/',
method: request.method,
headers: request.headers
},
serverResponse => {
// 第三步:收到服务器的响应
var body = ''
serverResponse.on('data', chunk => {
body += chunk
})
serverResponse.on('end', () => {
console.log('The data is ' + body)
// 第四步:将响应结果转发给浏览器
response.end(body)
})
}
)
.end()
})
server.listen(3000, () => {
console.log('The proxyServer is running at http://localhost:3000')
})1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20
.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.
server2.js
// server2.js(http://localhost:4000)
const http = require('http')
const data = { title: 'fontend', password: '123456' }
const server = http.createServer((request, response) => {
if (request.url === '/') {
response.end(JSON.stringify(data))
}
})
server.listen(4000, () => {
console.log('The server is running at http://localhost:4000')
})1.2.3.4.5.6.7.8.9.10.11.
上述代码经过两次跨域,值得注意的是浏览器向代理服务器发送请求,也遵循同源策略,最后在index.html文件打印出{"title":"fontend","password":"123456"}。
11.参考文章
- 九种跨域方式实现原理(完整版)
- postMessage可太有用了
- 面试题之Jsonp的理解及手写代码
12.写在最后
我们知道JSONP只支持GET请求,不支持IE10以下的浏览器,且存在安全性问题容易被恶意劫持。而CORS支持所有类型的HTTP请求,是跨域HTTP请求的根本解决方案,实际生产中,使用得比较多的跨域方案是cors和nginx反向代理。
责任编辑:武晓燕来源: 前端一码平川
相关推荐
- 使用Python编写Ping监测程序(python 测验)
-
Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;本文将介绍如何使用Python编写Ping监测程...
- 批量ping!有了这个小工具,python再也香不了一点
-
号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友。在咱们网工的日常工作中,经常需要检测多个IP地址的连通性。不知道你是否也有这样的经历:对着电脑屏...
- python之ping主机(python获取ping结果)
-
#coding=utf-8frompythonpingimportpingforiinrange(100,255):ip='192.168.1.'+...
- 网站安全提速秘籍!Nginx配置HTTPS+反向代理实战指南
-
太好了,你直接问到重点场景了:Nginx+HTTPS+反向代理,这个组合是现代Web架构中最常见的一种部署方式。咱们就从理论原理→实操配置→常见问题排查→高级玩法一层层剖开说,...
- Vue开发中使用iframe(vue 使用iframe)
-
内容:iframe全屏显示...
- Vue3项目实践-第五篇(改造登录页-Axios模拟请求数据)
-
本文将介绍以下内容:项目中的public目录和访问静态资源文件的方法使用json文件代替http模拟请求使用Axios直接访问json文件改造登录页,配合Axios进行登录请求,并...
- Vue基础四——Vue-router配置子路由
-
我们上节课初步了解Vue-router的初步知识,也学会了基本的跳转,那我们这节课学习一下子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只...
- Vue3.0权限管理实现流程【实践】(vue权限管理系统教程)
-
作者:lxcan转发链接:https://segmentfault.com/a/1190000022431839一、整体思路...
- swiper在vue中正确的使用方法(vue中如何使用swiper)
-
swiper是网页中非常强大的一款轮播插件,说是轮播插件都不恰当,因为它能做的事情太多了,swiper在vue下也是能用的,需要依赖专门的vue-swiper插件,因为vue是没有操作dom的逻辑的,...
- Vue怎么实现权限管理?控制到按钮级别的权限怎么做?
-
在Vue项目中实现权限管理,尤其是控制到按钮级别的权限控制,通常包括以下几个方面:一、权限管理的层级划分...
- 【Vue3】保姆级毫无废话的进阶到实战教程 - 01
-
作为一个React、Vue双修选手,在Vue3逐渐稳定下来之后,是时候摸摸Vue3了。Vue3的变化不可谓不大,所以,本系列主要通过对Vue3中的一些BigChanges做...
- Vue3开发极简入门(13):编程式导航路由
-
前面几节文章,写的都是配置路由。但是在实际项目中,下面这种路由导航的写法才是最常用的:比如登录页面,服务端校验成功后,跳转至系统功能页面;通过浏览器输入URL直接进入系统功能页面后,读取本地存储的To...
- vue路由同页面重定向(vue路由重定向到外部url)
-
在Vue中,可以使用路由的重定向功能来实现同页面的重定向。首先,在路由配置文件(通常是`router/index.js`)中,定义一个新的路由,用于重定向到同一个页面。例如,我们可以定义一个名为`Re...
- 那个 Vue 的路由,路由是干什么用的?
-
在Vue里,路由就像“页面导航的指挥官”,专门负责管理页面(组件)的切换和显示逻辑。简单来说,它能让单页应用(SPA)像多页应用一样实现“不同URL对应不同页面”的效果,但整个过程不会刷新网页。一、路...
- Vue3项目投屏功能开发!(vue投票功能)
-
最近接了个大屏项目,产品想在不同的显示器上展示大屏项目不同的页面,做出来的效果图大概长这样...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)