main.js
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const qs = require('querystring');
const { promisify } = require('util');
const readFileAsync = promisify(fs.readFile);
const proxy = require('./http-proxy');
const server = http.createServer();
server.on('request', (req, res) => {
let { pathname, path: pathStr } = url.parse(req.url);
console.log('請求的路徑爲:', pathname);
// 根路徑,響應首頁
if (pathname === '/') {
readFileAsync(path.join(__dirname, './index.html'))
.then((data) => {
res.end(data);
})
.catch((error) => {
res.write("服務器錯誤");
res.end();
console.log(error);
});
} else {
proxy(req, res);
}
});
server.listen(3000, "localhost", (error) => {
if (error) {
console.log('服務器啓動失敗!');
} else {
console.log('服務器啓動成功!');
}
});
http-proxy.js
const http = require("https");
const url = require("url");
const config = require("./config");
module.exports = (req, res) => {
// 得到請求的路徑
let { path: pathStr } = url.parse(req.url);
// 得到代理的配置項,對配置項進行遍歷
Object.entries(config).forEach(([key, value]) => {
// key: 需要代理的路徑的開頭部分
// value: 該代理的配置項
if (pathStr.startsWith(key)) {
proxy(req, res, value.target, value.pathRewrite);
}
});
function proxy(req, res, host, pathRewrite) {
// 替換路徑,換乘真正的請求路徑
if (pathRewrite) {
pathStr = pathStr.replace(pathRewrite.oldPath, pathRewrite.newPath);
}
// 將目標服務器域名和請求地址拼接起來創建請求
http.request(`${host}${pathStr}`, (response) => {
response.on('data', (bf) => {
// 響應客戶端
res.write(bf);
});
response.on('end', () => {
// 響應完成
res.end();
});
})
// 轉發請求
.end();
}
};
config.js
module.exports = {
'/api': {
target: 'https://m.you.163.com',
pathRewrite: {
oldPath: /\/api/,
newPath: ''
}
},
'/maoyansh': {
target: 'https://show.maoyan.com',
pathRewrite: null
},
'/ajax': {
target: 'https://m.maoyan.com'
}
}