node-proxy-server
引言
純前端開發的時候,很多業務場景需要搭建本地服務器,方便頁面瀏覽,
簡單列舉幾個好處,比如
- 局域網內多終端訪問
- 配合外網映射
- 解決介面跨域問題
我常用到的幾種本地搭建服務器的方式,比如
npm的serve package
- 全域安裝,
serve ./啟動,方便好用, - 直接啟動的話不支持跨域,
webpack-dev-server
- 一般使用在基于wepack的專案,普通H5搭建需要成本,
- 支持跨域,
node-proxy-server 鏈接
- 適用于普通頁面開發,配置簡單,node 命令啟動,
- 支持跨域,
node-proxy-server 原理
配置
配置介面地址的攔截,以及代理介面的地址,
let conifg = {
'/xxxx1': { // 需要攔截的本地請求路徑
target: 'http://xxxxxxxx.com', // 代理地址
port: 80, // 埠,默認80,某些地址可能是8080
},
'/xxxx2': {
target: 'http://xxxxxxxx.com',
port: 80,
}
// ...other path
};
中間代理服務器
主要利用nodejs的 http 和 fs模塊,創建一個中間服務器,接受頁面請求,再通過中間服務器去請求真實介面,回傳資料,
let http = require('http');
let fs = require('fs');
// 創建中間代理層http服務
let app = http.createServer(function (request, response) {});
攔截請求,轉發請求
根據配置中的設定的攔截路徑,攔截請求,并且轉發到真實地址中,
// 判斷是否存在代理地址
function hasProxy(url, request, response) {
for (const key in conifg) { // 如果存在多個攔截路徑
const { target, port } = conifg[key];
let info = target.split('//');
let opts = { // 請求引數
protocol: info[0],
host: info[1],
port: port || 80,
method: request.method,
path: url,
json: true,
headers: {}
}
proxy(opts, request, response);
return true;
}
return false;
}
// 代理轉發
function proxy(opts, request, response) {
// 請求真實代理介面
var proxyRequest = http.request(opts, function (proxyResponse) {
// 代理介面回傳資料,寫入本地response
proxyResponse.on('data', function (chunk) {
response.write(chunk, 'binary');
});
// 代理介面結束,通知本地response結束
proxyResponse.on('end', function () {
response.end();
});
response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
});
// 本地介面資料傳輸,通知代理介面請求
request.on('data', function (chunk) {
proxyRequest.write(chunk, 'binary');
});
// 本地請求結束,通知代理介面請求結束
request.on('end', function () {
proxyRequest.end();
});
}
普通資源請求
非攔截請求,直接通過,
// 普通請求和資源加載
fs.readFile(__dirname + url, function (err, data) {
if (err) {
console.log('請求失敗', err);
} else {
response.end(data);
}
});
原始碼
完整代碼,歡迎自取,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/249550.html
標籤:其他
上一篇:JAVA掃雷小游戲(待改進)
