前端跨域调用js方法解决方案设计(前端跨域调用js方法解决方案设计问题)

前端跨域调用js方法解决方案设计(前端跨域调用js方法解决方案设计问题)p id 0NUVB4T9 作者 一川 p p h5 1 写在前面 h5 p p id 0NUVB4TA 同域和跨域问题是老生常谈的问题 同源无外乎 主机 端口号 协议保持一致 当其中一个不一致的时候就是存在跨域问题 这时候就需要我们进行处理 p

大家好,我是讯享网,很高兴认识大家。




讯享网

                <p id="0NUVB4T9">作者:一川</p><p><h5>1.写在前面</h5></p><p id="0NUVB4TA">同域和跨域问题是老生常谈的问题,同源无外乎:主机、端口号、协议保持一致,当其中一个不一致的时候就是存在跨域问题,这时候就需要我们进行处理。</p><p id="0NUVB4TB">常见的跨域方案有以下九种:</p><p><ul><li id="0NUVB50C">JSONP</li><li id="0NUVB50D">CORS</li><li id="0NUVB50E">postMessage</li><li id="0NUVB50F">webSocket</li><li id="0NUVB50G">window.name + iframe</li><li id="0NUVB50H">document.domain + iframe</li><li id="0NUVB50I">location.hash + iframe</li><li id="0NUVB50J">nginx反向代理</li><li id="0NUVB50K">http-proxy</li></ul><h5>2.JSONP</h5></p><p id="0NUVB4TC">JSONP(JSON with Padding) 是JSON的一种‘使用模式’,可以跨域的获取到数据。</p><p id="0NUVB4TD">手写JSONP代码的思路是:</p><p><ul><li id="0NUVB50L">设置等待我们请求的url,将参数对象params的参数进行拼接得到一个字符串</li><li id="0NUVB50M">构造script</li><li id="0NUVB50N">js代码使用document.createElement创建一个script标签</li><li id="0NUVB50O">返回一个Promise,无论最终是返回成功还是失败的数据,都要对script标签进行移除</li></ul></p><p id="0NUVB4TE">请求页面代码index.html:</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2Ff8b87289j00r92n0l001id000ee00iop.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4TI">服务器代码:</p><p><blockquote id="0NUVB51F"><ul><li id="0NUVB50P">const express = require("express")<br/>const app = express()<br/>app.get("/say",(req,res)=&gt;{<br/>const {wd, cb} = req.query;<br/>console.log("wd", wd);<br/>res.end(`${cb}("Pingping i love you")`)<br/>app.listen(3000,()=&gt;{<br/>console.log(`this is server is running...`);<br/>})1.2.3.4.5.6.7.8.9.10.11.12.<br/></li></ul></blockquote></p><p id="0NUVB4TJ">服务器打印:</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F8ebe15fep00r92my2000hc000h8002km.png&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4TL">页面数据打印:</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F1f9e6508j00r92my2000pc000lg007wm.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4TN">我们看到当刘拉你去通过jsonp向后端请求时,后端接收请求后进行打印数据,而后向前端返回Pingping i love you在控制台进行打印。</p><p><h5>3.CORS</h5></p><p id="0NUVB4TO">我们知道JSONP也可以跨域,那为什么还要使用CORS呢?</p><p><ul><li id="0NUVB50Q">jsonp只可以使用 GET 方式提交</li><li id="0NUVB50R">不好调试,在调用失败的时候不会返回任何状态码</li><li id="0NUVB50S">安全性问题</li></ul></p><p id="0NUVB4TP">当提供JSONP的服务被恶意注入漏洞,那么它返回数据的JS内容就被人控制了,这样调用这个JSONP的网站都会存在这个漏洞,因此必须在确保JSONP内容安全可靠的时候才能进行使用。</p><p id="0NUVB4TQ">CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing),他允许浏览器向跨源服务器发送XMLHttpRequest请求,从而克服啦 AJAX 只能同源使用的限制。</p><p id="0NUVB4TR">CORS需要浏览器和服务器同时支持,整个 CORS通信过程,都是浏览器自动完成不需要用户参与,对于开发者来说,CORS的代码和正常的 AJAX 没有什么差别,浏览器一旦发现跨域请求,就会添加一些附加的头信息。</p><p id="0NUVB4TS">但是,CORS仅支持IE10以上的版本。</p><p><h5>index.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F2fce47c1j00r92n2h0012d000m600awp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>server01.js</h5><blockquote id="0NUVB51G"><ul><li id="0NUVB50T">const express = require("express");<br/>const app = express();<br/>app.use(express.static(__dirname));<br/>app.listen(3002,()=&gt;{<br/>console.log(`http://localhost:3002`);<br/>});1.2.3.4.5.6.<br/></li></ul></blockquote><h5>server02.js</h5><blockquote id="0NUVB51H"><ul><li id="0NUVB50U">const express = require("express")<br/>const app = express()<br/>app.get("/getData",(req,res)=&gt;{<br/>const {wd, cb} = req.query;<br/>console.log("wd", wd);<br/>res.end(`${cb}("Pingping i love you")`)<br/>app.listen(3001,()=&gt;{<br/>console.log(`this is server is running...`);<br/>})1.2.3.4.5.6.7.8.9.10.11.12.13.<br/></li></ul></blockquote></p><p id="0NUVB4U0">我们看到,当写好了ajax请求代码,在启动server01.js服务后,在浏览器向后端请求数据,我们发现出现了跨域报错。</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2Fc77a4814p00r92my2001kc000u0002lm.png&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4U2">那么我们需要在后端服务进行设置Access-Control-Allow-Origin实现跨域请求。</p><p><blockquote id="0NUVB51I"><ul><li id="0NUVB50V">const whitList = ["http://localhost:3002"]<br/>app.use((req, res, next)=&gt;{<br/>const origin = req.headers.origin;<br/>if(whitList.includes(origin)){<br/>// 设置哪个源可以访问我们<br/>res.setHeader("Access-Control-Allow-Origin",origin);<br/>// 允许携带哪个头访问我<br/>res.setHeader("Access-Control-Allow-Headers","name");<br/>// 允许哪个方法访问我 默认允许get post请求<br/>res.setHeader("Access-Control-Allow-Methods","PUT");<br/>// 允许携带cookie<br/>res.setHeader("Access-Control-Allow-Credentials",true);<br/>// 预检的存活时间<br/>res.setHeader("Access-Control-Max-Age",10);<br/>// 允许返回的头<br/>res.setHeader("Access-Control-Expose-Headers","name");<br/>if(req.method === "OPTIONS"){<br/>res.end();//OPTIONS请求不做任何处理<br/><br/>next()<br/>})1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.<br/></li></ul></blockquote></p><p id="0NUVB4U3">此时,我们看到:</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F39000f8cp00r92my2000bc000my0040m.png&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>4.postMessage</h5></p><p id="0NUVB4U5">postMessage是H5引入的API,postMessage()方法允许来自不同源的脚本采用异步方式进行有效的通信,可以实现跨文本文档、多窗口、跨域消息传递。多用于窗口间数据通信,这也使它成为跨域通信的一种有效的解决方案。</p><p id="0NUVB4U6">发送数据:</p><p id="0NUVB4U7">otherWindow.postMessage(message, targetOrigin, [transfer]);1.<br/></p><p><h5>pingping.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F47cb4900j00r92n52000ld000m2006op.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>onechuan.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F69a5eb7ej00r92n6g0017d000m500ayp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4UE">我们可以看到,在onechuan.html中通过postMessage请求并展示了pingping.html页面的数据,控制台出现了i love u onechuan。</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F8c3bbf37j00r92my2000gc000u0004wm.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>5.window.name+iframe</h5></p><p id="0NUVB4UG">window.name属性name 值在不同的页面(甚至不同域名)加载后依旧存在(如果没修改则值不会变化),并且可以支持非常长的 name 值(2MB)。并且使用window.name很方便。</p><p id="0NUVB4UH">name 在浏览器环境中是一个全局/window对象的属性,且当在 iframe 中加载新页面(可以是不同域的)时,name 的属性值依旧保持不变(只要不重新赋值)。name属性的值虽然不变,但对它的访问还是受到同域原则,不允许访问。所以我们要把iframe重新定向回原域,这样name的值也没变,并且可以访问了。</p><p><ul><li id="0NUVB510">a.html和b.html是同域的 http://localhost:3000</li><li id="0NUVB511">c.html 是独立的 http://localhost:3001</li><li id="0NUVB512">a.html获取c.html的数据</li><li id="0NUVB513">a.html先引用c.html,c把值放在window.name,把a引用的地址改为b.html</li></ul><h5>a.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F28ceff60j00r92n7n0021d000lp00gdp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4UL">b.html为中间代理页,与a.html同域,内容为空。</p><p><h5>c.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F98d1a92ej00r92n8l0009d000mu005dp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4UO">总结:通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。</p><p><h5>6.location.hash+iframe</h5></p><p id="0NUVB4UP">实现原理:a.html欲与c.html跨域相互通信,通过中间页b.html来实现。三个页面,不同域之间利用iframe的location.hash传值,相同域之间直接js访问来通信。</p><p id="0NUVB4UQ">路径后面的hash值可以用来通信,我们的目的从a想访问c,那么从a给c传一个hash值,c收到hash值后,c把hash值传递给b,那么b将结果放在a的hash值中。</p><p><h5>a.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2Fefd3242fj00r92n9v000nd000lo006sp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>b.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2Fefd3242fj00r92naf000nd000lo006sp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>c.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F8bd9f10ej00r92nb2000od000ly006ap.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4V4">在a.html页面通过iframe打开c.html页面,而c.html中创建iframe标签设置src为b.html,最终打开了b.html页面,能够在控制台打印hash值。</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F62611a81j00r92my2000ec000u0008jm.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>7.document.domain + iframe</h5></p><p id="0NUVB4V7">该方式只能用于二级域名相同的情况下,比如 a.onechuan.com 和 b.onechuan.com 适用于该方式。只需要给页面添加 document.domain ='onechuan.com' 表示二级域名都相同就可以实现跨域。</p><p id="0NUVB4V8">实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域。我们看个例子:页面a.onechuna.com:3000/a.html获取页面b.onechuan.com:3000/b.html中a的值</p><p id="0NUVB4V9">a.html</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F9697dc74j00r92ndh001dd000m800bxp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4VD">b.html</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2Ffeb797aej00r92ne2000bd000m0004rp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p id="0NUVB4VH">设置host:</p><p><blockquote id="0NUVB51J"><ul><li id="0NUVB514">127.0.0.1 a.onechuan.com<br/>127.0.0.1 b.onechuan.com1.2.<br/></li></ul></blockquote><h5>8.webSocket</h5></p><p id="0NUVB4VI">WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。</p><p id="0NUVB4VJ">实际使用的时候,我们会用封装好的Socket.io。</p><p><h5>websocket.html</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2Fd153f9b3j00r92nf3000sd000lj008lp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>server.js</h5><blockquote id="0NUVB51K"><ul><li id="0NUVB515">const WebSocket = require("ws");<br/>const wss = new WebSocket.Server({port:3000});<br/>wss.on("connection",ws=&gt;{<br/>ws.on("message",data=&gt;{<br/>console.log("data",data);<br/>ws.send("i love u onechuan")<br/>})1.2.3.4.5.6.7.8.<br/></li></ul></blockquote></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F1c920fb3p00r92my2000kc000po001qm.png&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2F594ebf05j00r92my20006c000ha005km.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>9.nginx反向代理</h5></p><p id="0NUVB4VQ">使用nginx反向代理实现跨域,是最简单的跨域方式。只需要修改nginx的配置即可解决跨域问题,支持所有浏览器,支持session,不需要修改任何代码,并且不会影响服务器性能。</p><p id="0NUVB4VR">实现思路:通过nginx配置一个代理服务器(域名与domain1相同,端口不同)做跳板机,反向代理访问domain2接口,并且可以顺便修改cookie中domain信息,方便当前域cookie写入,实现跨域登录。</p><p id="0NUVB4VS">先下载nginx,然后将nginx目录下的nginx.conf修改如下:</p><p><blockquote id="0NUVB51L"><ul><li id="0NUVB516">// proxy服务器<br/>server {<br/>listen       81;<br/>server_name  www.domain1.com;<br/>location / {<br/>proxy_pass   http://www.domain2.com:8080;  #反向代理<br/>proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名<br/>index  index.html index.htm;<br/># 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用<br/>add_header Access-Control-Allow-Origin http://www.domain1.com;  #当前端只跨域不带cookie时,可为*<br/>add_header Access-Control-Allow-Credentials true;<br/>}1.2.3.4.5.6.7.8.9.10.11.12.13.14.<br/></li></ul></blockquote></p><p id="0NUVB4VT">最后通过命令行nginx -s reload启动nginx。</p><p><h5>index.html</h5></p><p id="0NUVB4VU">var xhr = new XMLHttpRequest();<br/>// 前端开关:浏览器是否读写cookie<br/>xhr.withCredentials = true;<br/>// 访问nginx中的代理服务器<br/>xhr.open('get', 'http://www.domain1.com:81/?user=admin', true);<br/>xhr.send();1.2.3.4.5.6.<br/></p><p><h5>server.js</h5></p><p id="0NUVB4VV">var http = require('http');<br/>var server = http.createServer();<br/>var qs = require('querystring');<br/>server.on('request', function(req, res) {<br/>var params = qs.parse(req.url.substring(2));<br/>// 向前台写cookie<br/>res.writeHead(200, {<br/>'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly'   // HttpOnly:脚本无法读取<br/>});<br/>res.write(JSON.stringify(params));<br/>res.end();<br/>});<br/>server.listen('8080');<br/>console.log('Server is running at port 8080...');1.2.3.4.5.6.7.8.9.10.11.12.13.14.<br/></p><p><h5>10.http-proxy</h5></p><p id="0NUVB500">同源策略是浏览器需要遵循的标准,而如果是服务器向服务器请求就无需遵循同源策略。</p><p id="0NUVB501">代理服务器,需要做以下几个步骤:</p><p><ul><li id="0NUVB517">接受客户端请求 。</li><li id="0NUVB518">将请求转发给服务器。</li><li id="0NUVB519">拿到服务器 响应 数据。</li><li id="0NUVB51A">将 响应 转发给客户端。</li></ul></p><p id="0NUVB502">我们先来看个例子:本地文件index.html文件,通过代理服务器http://localhost:3000向目标服务器http://localhost:4000请求数据。</p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2Fcbb3a84dj00r92nhb001hd000ls00dgp.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>server.js</h5></p><p class="f_center"><img src="https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0321%2Fa5a0eaffj00r92nic001td000ba00k5p.jpg&thumbnail=660x2147483647&quality=80&type=jpg"/><br/></p><p><h5>server2.js</h5><blockquote id="0NUVB51M"><ul><li id="0NUVB51B">// server2.js(http://localhost:4000)<br/>const http = require('http')<br/>const data = { title: 'fontend', password: '123456' }<br/>const server = http.createServer((request, response) =&gt; {<br/>if (request.url === '/') {<br/>response.end(JSON.stringify(data))<br/><br/>server.listen(4000, () =&gt; {<br/>console.log('The server is running at http://localhost:4000')<br/>})1.2.3.4.5.6.7.8.9.10.11.<br/></li></ul></blockquote></p><p id="0NUVB509">上述代码经过两次跨域,值得注意的是浏览器向代理服务器发送请求,也遵循同源策略,最后在index.html文件打印出{"title":"fontend","password":"123456"}。</p><p><h5>11.参考文章</h5><ul><li id="0NUVB51C">九种跨域方式实现原理(完整版)</li><li id="0NUVB51D">postMessage可太有用了</li><li id="0NUVB51E">面试题之Jsonp的理解及手写代码</li></ul><h5>12.写在最后</h5></p><p id="0NUVB50A">我们知道JSONP只支持GET请求,不支持IE10以下的浏览器,且存在安全性问题容易被恶意劫持。而CORS支持所有类型的HTTP请求,是跨域HTTP请求的根本解决方案,实际生产中,使用得比较多的跨域方案是cors和nginx反向代理。</p><p id="0NUVB50B">责任编辑:武晓燕来源: 前端一码平川</p>

讯享网
小讯
上一篇 2025-06-12 07:27
下一篇 2025-06-15 16:41

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/191991.html