前端獲取數據時經常會遇到跨域問題,用 nginx 做反向代理就可以解決此問題。但是 nginx 屬於中間件代理,不同開發者佈署的 web 服務器地址可能不一樣,這樣 nginx 的配置就不能做到通用了。
如果能有一個客戶端代理,隨着項目源代碼提交,這樣就可以免去不同開發者的代理配置。webpack-dev-server 就是這樣的一個客戶端代理,但是如果項目沒有用到 webpack,那就沒辦法用了。那能不能仿照寫了一個簡單的 web 服務器,用於非 webpack 的項目呢。下面是代碼,望大佬們批評指正。
const request = require('request');
const express = require('express');
const path = require('path');
const app = express();
// 代理配置
const proxyTable = {
'/api': {
target: 'http://localhost/api'
}
};
app.use(function(req, res,next) {
const url = req.url;
if (req.method == 'OPTIONS') {
console.log('options_url: ', url);
// 設置cors 跨域
// res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
// res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
// res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// 設置 cookie
// res.header("Access-Control-Allow-Credentials", true);
res.status(200).send('OK');
return;
}
// console.log('req_url: ', url);
next();
});
// 設置靜態目錄
app.use(express.static(path.join(__dirname, 'static')));
app.use('/', function(req, res) {
const url = req.url;
const proxy = Object.keys(proxyTable);
let not_found = true;
for (let index = 0; index < proxy.length; index++) {
const k = proxy[index];
const i = url.indexOf(k);
if (i >= 0) {
not_found = false;
const element = proxyTable[k];
const newUrl = element.target + url.slice(i+k.length);
req.pipe(request({url: newUrl, timeout: 60000},(err)=>{
if(err){
console.log('error_url: ', err.code,url);
res.status(500).send('');
}
})).pipe(res);
break;
}
}
if(not_found) {
console.log('not_found_url: ', url);
res.status(404).send('Not found');
} else {
console.log('proxy_url: ', url);
}
});
// 監聽端口
const PORT = 8080;
app.listen(PORT, () => {
console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
PS:static 放靜態頁面