跨域和正則,算是我一直遺留的問題了,一直在想跨域服務器端配置不就好了,但是這個問題卻要求前端必須處理,無所謂既然定義爲遺留,我就總要弄清楚;正則就不用講了,一致認爲很重要但是一直覺得使用到的就那幾個,搜出來用就好了,其實早晚都要明白的,如果畢業快兩個月實習一年多了還不弄明白就有點說不過去了(因爲我是一個懷揣大神夢的菜鳥)。
跨域:
1.廣義上的跨域 :
1.) 資源跳轉: A鏈接、重定向、表單提交
2.) 資源嵌入: <link>、<script>、<img>、<frame>等dom標籤,還有樣式中background:url()、@font-face()等文件外鏈
3.) 腳本請求: js發起的ajax請求、dom和js對象的跨域操作等
2.跨域的產生
跨域是由於瀏覽器的同源策略而產生的,同源策略我理解就是瀏覽器爲了自衛防止攻擊而生成的一種約定,“同源”即協議,域名以及端口均相同。
同源策略對以下有限制:
1.) Cookie、LocalStorage 和 IndexDB 無法讀取
2.) DOM 和 Js對象無法獲得
3.) AJAX 請求不能發送
3.跨域的解決方案
3.1通過jsonp跨域
類似外鏈加入css,js以及圖片一樣,動態生成script,再請求一個帶參請求【jsonp只能進行get請求】
實現方式:
。原生js:
<script>
var script = document.createElement('script');
script.type = 'text/javascript';
// 傳參並指定回調執行函數爲onBack
script.src = 'http://www.domain2.com:8080/login?user=admin&callback=onBack';
document.head.appendChild(script);
// 回調執行函數
function onBack(res) {
alert(JSON.stringify(res));
}
</script>
。ajax
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 請求方式爲jsonp
jsonpCallback: "onBack", // 自定義回調函數名
data: {}
});
。vue.js
this.$http.jsonp('http://www.domain2.com:8080/login', {
params: {},
jsonp: 'onBack'
}).then((res) => {
console.log(res);
})
3.2document.domain+iframe
兩個頁面通過js強制設置document.domain相同實現跨域【主域相同,子域不同】
實現如下(設置document.domain都相同):
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/b.html)
<script>
document.domain = 'domain.com';
// 獲取父窗口中變量
alert('get js data from parent ---> ' + window.parent.user);
</script>
3.3 location.hash + iframe跨域
a和b不同域,ac同域,ab通過location.hash進行藉助中間頁c實現跨域
實現如下:
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');
// 監聽a.html傳來的hash值,再傳給c.html
window.onhashchange = function () {
iframe.src = iframe.src + location.hash;
};
</script>
3.)c.html:(http://www.domain1.com/c.html)
<script>
// 監聽b.html傳來的hash值
window.onhashchange = function () {
// 再通過操作同域a.html的js回調,將結果傳回
window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
};
</script>
3.4 window.name + iframe跨域
3.5 postMessage跨域
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是爲數不多可以跨域操作的window屬性之一,它可用於解決以下方面的問題:
a.) 頁面和其打開的新窗口的數據傳遞
b.) 多窗口之間消息傳遞
c.) 頁面與嵌套的iframe消息傳遞
d.) 上面三個場景的跨域數據傳遞
用法:postMessage(data,origin)方法接受兩個參數
data: html5規範支持任意基本類型或可複製的對象,但部分瀏覽器只支持字符串,所以傳參時最好用JSON.stringify()序列化。
origin: 協議+主機+端口號,也可以設置爲"*",表示可以傳遞給任意窗口,如果要指定和當前窗口同源的話設置爲"/"。
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傳送跨域數據
iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
};
// 接受domain2返回數據
window.addEventListener('message', function(e) {
alert('data from domain2 ---> ' + e.data);
}, false);
</script>
2.)b.html:(http://www.domain2.com/b.html)
<script>
// 接收domain1的數據
window.addEventListener('message', function(e) {
alert('data from domain1 ---> ' + e.data);
var data = JSON.parse(e.data);
if (data) {
data.number = 16;
// 處理後再發回domain1
window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
}
}, false);
</script>
3.6 跨域資源共享(CORS)
普通跨域請求:只服務端設置Access-Control-Allow-Origin即可,前端無須設置,若要帶cookie請求:前後端都需要設置。
需注意的是:由於同源策略的限制,所讀取的cookie爲跨域請求接口所在域的cookie,而非當前頁。如果想實現當前頁cookie的寫入,可參考下文:七、nginx反向代理中設置proxy_cookie_domain 和 八、NodeJs中間件代理中cookieDomainRewrite參數的設置。
目前,所有瀏覽器都支持該功能(IE8+:IE8/9需要使用XDomainRequest對象來支持CORS)),CORS也已經成爲主流的跨域解決方案。
1、 前端設置:
1.)原生ajax
// 前端設置是否帶cookie
xhr.withCredentials = true;
示例代碼:
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);
}
};
2.)jQuery ajax
$.ajax({
...
xhrFields: {
withCredentials: true // 前端設置是否帶cookie
},
crossDomain: true, // 會讓請求頭中包含跨域的額外信息,但不會含cookie
...
});
3.)vue框架
在vue-resource封裝的ajax組件中加入以下代碼:
Vue.http.options.credentials = true
後臺設置
Nodejs後臺示例:
var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request', function(req, res) {
var postData = '';
// 數據塊接收中
req.addListener('data', function(chunk) {
postData += chunk;
});
// 數據接收完畢
req.addListener('end', function() {
postData = qs.parse(postData);
// 跨域後臺設置
res.writeHead(200, {
'Access-Control-Allow-Credentials': 'true', // 後端允許發送Cookie
'Access-Control-Allow-Origin': 'http://www.domain1.com', // 允許訪問的域(協議+域名+端口)
/*
* 此處設置的cookie還是domain2的而非domain1,因爲後端也不能跨域寫cookie(nginx反向代理可以實現),
* 但只要domain2中寫入一次cookie認證,後面的跨域接口都能從domain2中獲取cookie,從而實現所有的接口都能跨域訪問
*/
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly的作用是讓js無法讀取cookie
});
res.write(JSON.stringify(postData));
res.end();
});
});
server.listen('8080');
console.log('Server is running at port 8080...');
3.7nginx
3.8 node.js中間價
3.9 WebSocket協議跨域
WebSocket protocol是HTML5一種新的協議。它實現了瀏覽器與服務器全雙工通信,同時允許跨域通訊,是server push技術的一種很好的實現。
原生WebSocket API使用起來不太方便,我們使用Socket.io,它很好地封裝了webSocket接口,提供了更簡單、靈活的接口,也對不支持webSocket的瀏覽器提供了向下兼容。
1.)前端代碼:
<div>user input:<input type="text"></div>
<script src="./socket.io.js"></script>
<script>
var socket = io('http://www.domain2.com:8080');
// 連接成功處理
socket.on('connect', function() {
// 監聽服務端消息
socket.on('message', function(msg) {
console.log('data from server: ---> ' + msg);
});
// 監聽服務端關閉
socket.on('disconnect', function() {
console.log('Server socket has closed.');
});
});
document.getElementsByTagName('input')[0].onblur = function() {
socket.send(this.value);
};
</script>
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...');
// 監聽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.');
});
});
正則
RegExp表示正則表達式,new RegExp(pattern, attributes); patten:正則表達式,attributes:修飾符