深刻跨域問題(1) - 初識 CORS 跨域資源共享;javascript
深刻跨域問題(4) - 利用 代理服務器 解決跨域(本篇)java
在上面的文章中,咱們依此瞭解到,CORS
,JSONP
兩種方式實現跨域請求。node
這兩種方法,都須要 先後端進行配合 纔可以正確地處理跨域問題。 今天介紹一種方法,不須要先後端配合,前端可獨立完成。jquery
衆所周知,同源策略是瀏覽器須要遵循的標準,重點是 瀏覽器 ,若是,是服務器是否是就不用遵照了呢 ???ajax
這是,咱們的一個猜測,非瀏覽器之間,不用遵行同源策略,先來測試一下:json
const http = require('http');
const options = {
hostname: '127.0.0.1', // 注意這裏不要添加 http 前綴
port: 4000, // 服務器端口號
path: '/', // 訪問路徑
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
}
};
const request = http.request(options, (serverResponse) => {
var body = '';
serverResponse.on('data', (chunk) => {
body += chunk;
});
serverResponse.on('end', () => {
console.log('The data is ' + body);
})
});
request.end();
複製代碼
服務器,發起一個POST請求後端
PS: 在瀏覽器中 POST 方法下 Content-Type
爲 application/json;
,會觸發 預請求 (請看我以前的文章)。api
const http = require('http');
const data = { name: 'BruceLee', 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');
});
複製代碼
注意:咱們沒有在服務器內部,加入任何與 CORS 跨域資源共享的首部字段 。
測試結果代表,經過 NODE
發起請求能夠避免 瀏覽器 的同源策略。
代理服務器,須要作如下幾個步驟:
這是簡單的文字解析,下方爲圖解流程:
這就是,代理服務器的工做機制(PS:畫的垃圾,哈哈哈)。
在瞭解,代理服務器的工做機制以後,下面咱們將用 NODE 實現代理服務器。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax測試</title>
</head>
<body>
<script src="./node_modules/jquery/dist/jquery.min.js"></script>
<script> var data = { name: 'BruceLee', password: '123456' }; $.ajax({ url: "http://localhost:3000", type: "post", data: JSON.stringify(data), contentType: 'application/json;charset=utf-8', success: function (result) { console.log(result); }, error: function (msg) { console.log(msg); } }) </script>
</body>
</html>
複製代碼
一樣,你能夠換成,PUT,DELETE 等方法,進行測試。
const http = require('http');
// 第一步:接受客戶端請求
const server = http.createServer((request, response) => {
// 代理服務器,直接和瀏覽器直接交互,也須要設置:CORS 的首部字段
response.writeHead(200, {
'Access-Control-Allow-Origin': '*', // 設置 optins 方法容許全部服務器訪問
'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');
});
複製代碼
須要咱們注意的是:代理服務器,直接與瀏覽器相鏈接,也必須須要遵照 瀏覽器的同源策略,
const http = require('http');
const data = { name: 'BruceLee', 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');
});
複製代碼
爲了篇幅仍然較小,我採用了較爲簡潔的代碼,你能夠本身多試試 好比:PUT,DELETE 方法。
實驗結果:
成功避免了跨域請求。
如今,咱們已經完成了,代理服務器解決跨域問題了,而且不須要後臺作任何設置。
代理服務器是現代化的前端經常使用的手段,另外還有反向代理,等等衆多方式實現跨域請求。