前端跨域解决方案总结
前端跨域解決方案總結
- 一、什么是跨域?
- 二、為什么會產(chǎn)生跨域
- 三、常見的跨域場景
- 四、9種跨域解決方案
- 1、JSONP跨域
- 1、概述
- 2、實現(xiàn)流程
- 3、jsonp簡單實現(xiàn)
- 1)、原生JS實現(xiàn)
- 2)jquery Ajax實現(xiàn):
- 3)Vue axios實現(xiàn):
- 4)、后端node.js代碼:
- 2、跨域資源共享(CORS)
- 1、概述
- 2、跨域是瀏覽器還是服務器的限制?
- 3、預檢請求
- 1)、預檢請求定義
- 2)、預檢請求示例
- 4、CORS 與認證
- 5、這種方法如果后端是采用node開發(fā)的,可以使用 CORS 模塊
- 6、補充,原生ajax和jquery的ajax
- 3、nginx代理跨域
- 1、nginx配置解決iconfont跨域
- 2、nginx反向代理接口跨域
- 4、nodejs中間件代理跨域
- 1)非vue框架的跨域
- 2)vue框架的跨域
- 5、document.domain + iframe跨域
- 6、location.hash + iframe跨域
- 7、window.name + iframe跨域
- 8、postMessage跨域
- 9、WebSocket協(xié)議跨域
- 10、小結
一、什么是跨域?
在前端領域中,跨域是指瀏覽器允許向服務器發(fā)送跨域請求,從而克服Ajax只能同源使用的限制。二、為什么會產(chǎn)生跨域
因為瀏覽器內部有一種約定叫做同源策略它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,瀏覽器很容易受到XSS、CSFR等攻擊。
那么什么叫做同源策略呢?
同源策略限制以下幾種行為:
| 2、DOM和JS對象無法獲得 |
| 3、AJAX 請求不能發(fā)送 |
三、常見的跨域場景
四、9種跨域解決方案
1、JSONP跨域
1、概述
JSONP是JSON with Padding的略稱。它是一個非官方的協(xié)議,它允許在服務器端集成Script tags返回至客戶端,通過javascript callback的形式實現(xiàn)跨域訪問
script 標簽 src 屬性中的鏈接卻可以訪問跨域的js腳本,利用這個特性,服務端不再返回JSON格式的數(shù)據(jù),而是返回一段調用某個函數(shù)的js代碼,在src中進行了調用,這樣實現(xiàn)了跨域。
2、實現(xiàn)流程
1、設定一個script標簽
<script src="http://jsonp.js?callback=xxx"></script>2、callback定義了一個函數(shù)名,而遠程服務端通過調用指定的函數(shù)并傳入?yún)?shù)來實現(xiàn)傳遞參數(shù),將fn(response)傳遞回客戶端
$callback = !empty($_GET['callback']) ? $_GET['callback'] : 'callback'; echo $callback.'(.json_encode($data).)';3、客戶端接收到返回的js腳本,開始解析和執(zhí)行fn(response)
3、jsonp簡單實現(xiàn)
一個簡單的jsonp實現(xiàn),其實就是拼接url,然后將動態(tài)添加一個script元素到頭部
jsonp的缺點:只能發(fā)送get一種請求。
1)、原生JS實現(xiàn)
前端示例
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>測試</title> </head><body><script>let script = document.createElement('script');script.type = 'text/javascript';// 傳參一個回調函數(shù)名給后端,方便后端返回時執(zhí)行這個在前端定義的回調函數(shù)script.src = 'http://localhost:5000/login?callback=handleCallback';document.head.appendChild(script);// 回調執(zhí)行函數(shù)function handleCallback(res) {alert(JSON.stringify(res));}</script> </body></html>2)jquery Ajax實現(xiàn):
$.ajax({url: 'http://localhost:5000/login',type: 'get',dataType: 'jsonp', // 請求方式為jsonpjsonpCallback: "handleCallback", // 自定義回調函數(shù)名data: {} });3)Vue axios實現(xiàn):
axios.jsonp('http://localhost:5000/login', {params: {},jsonp: 'handleCallback' }).then((res) => {console.log(res); })4)、后端node.js代碼:
const http = require('http'); const url = require('url');const port = 5000; const data = { 'data': 'world' };http.createServer(function (req, res) {console.log(req.url) ///login?callback=handleCallbackconst params = url.parse(req.url, true);console.log(params)/* Url {protocol: null,slashes: null,auth: null,host: null,port: null,hostname: null,hash: null,search: '?callback=handleCallback',query: [Object: null prototype] { callback: 'handleCallback' },pathname: '/login',path: '/login?callback=handleCallback',href: '/login?callback=handleCallback'}*/if (params.query.callback) {console.log(params.query.callback); //handleCallback//jsonplet str = params.query.callback + '(' + JSON.stringify(data) + ')';//handleCallback({data: "world"})res.end(str);} else {res.end();} }).listen(port, function () {console.log(`Server is running at port ${port}...`); });2、跨域資源共享(CORS)
1、概述
Cross-origin Resource Sharing 中文名稱 “跨域資源共享” 簡稱 “CORS”,它突破了一個請求在瀏覽器發(fā)出只能在同源的情況下向服務器獲取數(shù)據(jù)的限制。
它允許瀏覽器向跨域服務器,發(fā)出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。
CORS需要瀏覽器和服務器同時支持。目前,所有瀏覽器都支持該功能,IE瀏覽器不能低于IE10。
2、跨域是瀏覽器還是服務器的限制?
從一段示例開始
創(chuàng)建 index.html 使用 fetch 調用 http://127.0.0.1:3011/api/data
創(chuàng)建 client.js 用來加載上面 index.html。設置端口為 3010。
const http = require('http'); const fs = require('fs'); const PORT = 3010; http.createServer((req, res) => {fs.createReadStream('index.html').pipe(res); }).listen(PORT);創(chuàng)建 server.js 開啟一個服務,根據(jù)不同的請求返回不同的響應。設置端口為 3011。
const http = require('http'); const PORT = 3011;http.createServer((req, res) => {const url = req.url;console.log('request url: ', url);if (url === '/api/data') {return res.end('ok!');}if (url === '/script') {return res.end('console.log("hello world!");');} }).listen(PORT);console.log('Server listening on port ', PORT);運行上面的 client.js、server.js 瀏覽器輸入 http://127.0.0.1:3010 在 Chrome 瀏覽器中打開 Network 項查看請求信息,如下所示:
使用 fetch 請求的 127.0.0.1:3011/api/data 接口,在請求頭里可以看到有 Origin 字段,顯示了我們當前的請求信息。另外還有三個 Sec-Fetch-* 開頭的字段
其中 Sec-Fetch-Mode 表示請求的模式
Sec-Fetch-Site 表示的是這個請求是同源還是跨域,由于我們的請求都是由 3010 端口發(fā)出去請求 3011 端口,是不符合同源策略的.
看下瀏覽器 Console 下的日志信息,根據(jù)提示得知原因是從 “http://127.0.0.1:3010” 訪問 “http://127.0.0.1:3011/api/data” 被 CORS 策略阻止了,沒有 “Access-Control-Allow-Origin” 標頭
在看下服務端的日志,因為請求 3011 服務,所以就看下 3011 服務的日志信息:
在服務端是有收到請求信息的,說明服務端是正常工作的。
所以最終的結論
瀏覽器限制了從腳本內發(fā)起的跨源 HTTP 請求,例如 XMLHttpRequest 和我們本示例中使用的 Fetch API 都是遵循的同源策略。
3、預檢請求
預檢請求是在發(fā)送實際的請求之前,客戶端會先發(fā)送一個 OPTIONS 方法的請求向服務器確認,如果通過之后,瀏覽器才會發(fā)起真正的請求,這樣可以避免跨域請求對服務器的用戶數(shù)據(jù)造成影響。
看到這里你可能有疑問為什么上面的示例沒有預檢請求?因為 CORS 將請求分為了兩類:簡單請求和非簡單請求。我們上面的情況屬于簡單請求,所以也就沒有了預檢請求。
讓我們繼續(xù)在看下簡單請求和非簡單請求是如何定義的。
1)、預檢請求定義
例如,如果請求頭的 Content-Type 為 application/json 就會觸發(fā) CORS 預檢請求,這里也會稱為 “非簡單請求”。
2)、預檢請求示例
設置客戶端
為 index.html 里的 fetch 方法增加一些設置,設置請求的方法為 PUT,請求頭增加一個自定義字段 Test-Cors。
上述代碼在瀏覽器執(zhí)行時會發(fā)現(xiàn)是一個非簡單請求,就會先執(zhí)行一個預檢請求,
再通過控制臺看一下此時的信息顯示
Access-Control-Request-Method 告訴服務器,實際請求將使用 PUT 方法。
Access-Control-Request-Headers 告訴服務器,實際請求將使用兩個頭部字段 content-type,test-cors。這里如果 content-type 指定的為簡單請求中的幾個值,Access-Control-Request-Headers 在告訴服務器時,實際請求將只有 test-cors 這一個頭部字段。
此時還是處于跨域狀態(tài),因為我們并沒有設置服務端。所以預檢之后的請求依舊報紅,顯示跨域,如下圖
為了解決跨域,現(xiàn)在設置服務端
上面講解了客戶端的設置,同樣的要使請求能夠正常響應,還需服務端的支持。
修改我們的 server.js 重點是設置 Response Headers 代碼如下所示:
const http = require('http'); const PORT = 3011;http.createServer((req, res) => {const url = req.url;console.log('request url: ', url);if (url === '/api/data') {res.writeHead(200, {'Access-Control-Allow-Origin': 'http://127.0.0.1:3010','Access-Control-Allow-Headers': 'Test-CORS, Content-Type','Access-Control-Allow-Methods': 'PUT,DELETE','Access-Control-Max-Age': 86400});res.end()}if (url === '/script') {res.writeHead(200, {'Access-Control-Allow-Origin': 'http://127.0.0.1:3010','Access-Control-Allow-Headers': 'Test-CORS, Content-Type','Access-Control-Allow-Methods': 'PUT,DELETE','Access-Control-Max-Age': 86400});res.end()} }).listen(PORT);console.log('Server listening on port ', PORT);為什么是以上配置?首先預檢請求時,瀏覽器給了服務器幾個重要的信息 Origin、Method 為 PUT、Headers 為 content-type,test-cors 服務端在收到之后,也要做些設置,給予回應。
Access-Control-Allow-Origin 表示 “http://127.0.0.1:3010” 這個請求源是可以訪問的,該字段也可以設置為 “*” 表示允許任意跨源請求。
Access-Control-Allow-Methods 表示服務器允許客戶端使用 PUT、DELETE 方法發(fā)起請求,可以一次設置多個,表示服務器所支持的所有跨域方法,而不單是當前請求那個方法,這樣好處是為了避免多次預檢請求。
Access-Control-Allow-Headers 表示服務器允許請求中攜帶 Test-CORS、Content-Type 字段,也可以設置多個。
Access-Control-Max-Age 表示該響應的有效期,單位為秒。在有效時間內,瀏覽器無須為同一請求再次發(fā)起預檢請求。還有一點需要注意,該值要小于瀏覽器自身維護的最大有效時間,否則是無效的。
通過上面的方法,便可以解決跨域
4、CORS 與認證
對于跨域的 XMLHttpRequest 或 Fetch 請求,瀏覽器是不會發(fā)送身份憑證信息的。例如我們要在跨域請求中發(fā)送 Cookie 信息,就要做些設置:
為了能看到效果,我先自定義了一個 cookie 信息 id=NodejsRoadmap。
現(xiàn)在我們先不調整服務端,看一下是什么情況
通過查看控制臺,發(fā)現(xiàn)跨域了
這樣請求就可以正常發(fā)送了,不存在跨域了
5、這種方法如果后端是采用node開發(fā)的,可以使用 CORS 模塊
const http = require('http'); const PORT = 3011; const corsMiddleware = require('cors')({origin: 'http://127.0.0.1:3010',methods: 'PUT,DELETE',allowedHeaders: 'Test-CORS, Content-Type',maxAge: 1728000,credentials: true, });http.createServer((req, res) => {const { url, method } = req;console.log('request url:', url, ', request method:', method);const nextFn = () => {if (method === 'PUT' && url === '/api/data') {return res.end('ok!');}return res.end();}corsMiddleware(req, res, nextFn); }).listen(PORT);如果你用的 Express.js 框架,使用起來也很簡單,如下所示:
const express = require('express') const cors = require('cors') const app = express()app.use(cors());6、補充,原生ajax和jquery的ajax
原生ajax
var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容// 前端設置是否帶cookie xhr.withCredentials = true;xhr.open('post', 'http://www.domain2.com:8080/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);} };jquery ajax
$.ajax({...xhrFields: {withCredentials: true // 前端設置是否帶cookie},crossDomain: true, // 會讓請求頭中包含跨域的額外信息,但不會含cookie... });3、nginx代理跨域
1、nginx配置解決iconfont跨域
瀏覽器跨域訪問js、css、img等常規(guī)靜態(tài)資源被同源策略許可,但iconfont字體文件(eot|otf|ttf|woff|svg)例外,此時可在nginx的靜態(tài)資源服務器中加入以下配置。
location / {add_header Access-Control-Allow-Origin *; }2、nginx反向代理接口跨域
nginx具體配置:
server {listen 3011;server_name localhost;location / {if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' 'http://127.0.0.1:3010';add_header 'Access-Control-Allow-Methods' 'PUT,DELETE';add_header 'Access-Control-Allow-Headers' 'Test-CORS, Content-Type';add_header 'Access-Control-Max-Age' 1728000;add_header 'Access-Control-Allow-Credentials' 'true';add_header 'Content-Length' 0;return 204;}add_header 'Access-Control-Allow-Origin' 'http://127.0.0.1:3010';add_header 'Access-Control-Allow-Credentials' 'true';proxy_pass http://127.0.0.1:30011;proxy_set_header Host $host;} }4、nodejs中間件代理跨域
1)非vue框架的跨域
使用node + express + http-proxy-middleware搭建一個proxy服務器。
前端代碼:
中間件服務器代碼:
var express = require('express'); var proxy = require('http-proxy-middleware'); var app = express();app.use('/', proxy({// 代理跨域目標接口target: 'http://www.domain2.com:8080',changeOrigin: true,// 修改響應頭信息,實現(xiàn)跨域并允許帶cookieonProxyRes: function(proxyRes, req, res) {res.header('Access-Control-Allow-Origin', 'http://www.domain1.com');res.header('Access-Control-Allow-Credentials', 'true');},// 修改響應信息中的cookie域名cookieDomainRewrite: 'www.domain1.com' // 可以為false,表示不修改 }));app.listen(3000); console.log('Proxy server is listen at port 3000...');2)vue框架的跨域
詳情請查看我的另一篇文章
vue項目怎樣解決跨域問題呢?
5、document.domain + iframe跨域
1)父窗口:(http://www.domain.com/a.html)
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe> <script>document.domain = 'domain.com';var user = 'admin'; </script>2)子窗口:(http://child.domain.com/a.html)
<script>document.domain = 'domain.com';// 獲取父窗口中變量console.log('get js data from parent ---> ' + window.parent.user); </script>6、location.hash + iframe跨域
具體實現(xiàn):A域:a.html -> B域:b.html -> A域:c.html,a與b不同域只能通過hash值單向通信,b與c也不同域也只能單向通信,但c與a同域,所以c可通過parent.parent訪問a頁面所有對象。
1)a.html:(http://www.domain1.com/a.html)
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe> <script>var iframe = document.getElementById('iframe');// 向b.html傳hash值setTimeout(function() {iframe.src = iframe.src + '#user=admin';}, 1000);// 開放給同域c.html的回調方法function onCallback(res) {alert('data from c.html ---> ' + res);} </script>2)b.html:(http://www.domain2.com/b.html)
<iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe> <script>var iframe = document.getElementById('iframe');// 監(jiān)聽a.html傳來的hash值,再傳給c.htmlwindow.onhashchange = function () {iframe.src = iframe.src + location.hash;}; </script>3)c.html:(http://www.domain1.com/c.html)
<script>// 監(jiān)聽b.html傳來的hash值window.onhashchange = function () {// 再通過操作同域a.html的js回調,將結果傳回window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));}; </script>7、window.name + iframe跨域
window.name屬性的獨特之處:name值在不同的頁面(甚至不同域名)加載后依舊存在,并且可以支持非常長的 name 值(2MB)。
1)a.html:(http://www.domain1.com/a.html)
var proxy = function(url, callback) {var state = 0;var iframe = document.createElement('iframe');// 加載跨域頁面iframe.src = url;// onload事件會觸發(fā)2次,第1次加載跨域頁,并留存數(shù)據(jù)于window.nameiframe.onload = function() {if (state === 1) {// 第2次onload(同域proxy頁)成功后,讀取同域window.name中數(shù)據(jù)callback(iframe.contentWindow.name);destoryFrame();} else if (state === 0) {// 第1次onload(跨域頁)成功后,切換到同域代理頁面iframe.contentWindow.location = 'http://www.domain1.com/proxy.html';state = 1;}};document.body.appendChild(iframe);// 獲取數(shù)據(jù)以后銷毀這個iframe,釋放內存;這也保證了安全(不被其他域frame js訪問)function destoryFrame() {iframe.contentWindow.document.write('');iframe.contentWindow.close();document.body.removeChild(iframe);} };// 請求跨域b頁面數(shù)據(jù) proxy('http://www.domain2.com/b.html', function(data){alert(data); });2)proxy.html:(http://www.domain1.com/proxy.html)
?中間代理頁,與a.html同域,內容為空即可。
3)b.html:(http://www.domain2.com/b.html)
通過iframe的src屬性由外域轉向本地域,跨域數(shù)據(jù)即由iframe的window.name從外域傳遞到本地域。這個就巧妙地繞過了瀏覽器的跨域訪問限制,但同時它又是安全操作。
8、postMessage跨域
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是為數(shù)不多可以跨域操作的window屬性之一,它可用于解決以下方面的問題:
1、頁面和其打開的新窗口的數(shù)據(jù)傳遞
2、多窗口之間消息傳遞
3、頁面與嵌套的iframe消息傳遞
4、上面三個場景的跨域數(shù)據(jù)傳遞
用法:postMessage(data,origin)方法接受兩個參數(shù):
data: html5規(guī)范支持任意基本類型或可復制的對象,但部分瀏覽器只支持字符串,所以傳參時最好用JSON.stringify()序列化。
origin: 協(xié)議+主機+端口號,也可以設置為"*",表示可以傳遞給任意窗口,如果要指定和當前窗口同源的話設置為"/"。
1)a.html:(http://www.domain1.com/a.html)
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe> <script> var iframe = document.getElementById('iframe');iframe.onload = function() {var data = {name: 'aym'};// 向domain2傳送跨域數(shù)據(jù)iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');};// 接受domain2返回數(shù)據(jù)window.addEventListener('message', function(e) {alert('data from domain2 ---> ' + e.data);}, false); </script>2)b.html:(http://www.domain2.com/b.html)
<script>// 接收domain1的數(shù)據(jù)window.addEventListener('message', function(e) {alert('data from domain1 ---> ' + e.data);var data = JSON.parse(e.data);if (data) {data.number = 16;// 處理后再發(fā)回domain1window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');}}, false); </script>9、WebSocket協(xié)議跨域
WebSocket protocol是HTML5一種新的協(xié)議。它實現(xiàn)了瀏覽器與服務器全雙工通信,同時允許跨域通訊,是server push技術的一種很好的實現(xiàn)。
原生WebSocket API使用起來不太方便,我們使用Socket.io,它很好地封裝了webSocket接口,提供了更簡單、靈活的接口,也對不支持webSocket的瀏覽器提供了向下兼容。
1)前端代碼:
2)Nodejs socket后臺:
var http = require('http'); var socket = require('socket.io');// 啟http服務 var server = http.createServer(function(req, res) {res.writeHead(200, {'Content-type': 'text/html'});res.end(); });server.listen('8080'); console.log('Server is running at port 8080...');// 監(jiān)聽socket連接 socket.listen(server).on('connection', function(client) {// 接收信息client.on('message', function(msg) {client.send('hello:' + msg);console.log('data from client: ---> ' + msg);});// 斷開處理client.on('disconnect', function() {console.log('Client socket has closed.'); }); });10、小結
以上就是9種常見的跨域解決方案,jsonp(只支持get請求,支持老的IE瀏覽器)適合加載不同域名的js、css,img等靜態(tài)資源;CORS(支持所有類型的HTTP請求,但瀏覽器IE10以下不支持)適合做ajax各種跨域請求;Nginx代理跨域和nodejs中間件跨域原理都相似,都是搭建一個服務器,直接在服務器端請求HTTP接口,這適合前后端分離的前端項目調后端接口。document.domain+iframe適合主域名相同,子域名不同的跨域請求。postMessage、websocket都是HTML5新特性,兼容性不是很好,只適用于主流瀏覽器和IE10+。
參考自
https://www.imooc.com/article/291931
https://mp.weixin.qq.com/s/OG8Vb1Rc1Md4ON7usSu90A
總結
以上是生活随笔為你收集整理的前端跨域解决方案总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [链接]Python中的metaclas
- 下一篇: 9种常见的前端跨域解决方案(详解)