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);
}
});
源碼
完整代碼,歡迎自取。