nodejs简易代理服务器

Posted on 2021-05-10 11:14:39
Author: 可乐小可爱メ
1. 背景 

请求三方服务,因为服务器在海外, 网络延迟高, 实际部署上线后, 各种接口全都超时,严重影响实用效率.


2. 技术设计

  通过加一层 proxy server 做转发

        user --> client. --> proxy server --> business server .    

3. 代码实现

    3.1 代码结构

    

    3.2 

        proxy.js

const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const target = require("./.TARGET");

const app = express();
app.get("/", (req, res) => {
res.send("express 20010 home");
});

app.use(
"/api",
createProxyMiddleware({
target,
changeOrigin: true,
pathRewrite: {
"^/api": "", // rewrite path
},
})
);
app.listen(20010);

        

    shell.js

const fs = require("fs");
const shell = require("shelljs");
const { resolve } = require("path");
const order = process.argv.slice(2);
if (!order || order.length === 0) {
shell.echo("pls add target host!");
shell.exit(1);
}

const target = order[0].split("=")[1];
if (!target.startsWith("http")) {
return console.error("target error!");
}
fs.writeFile(
resolve(__dirname, ".TARGET"),
`module.exports = "${target}";`,
(err) => {
if (err) {
return console.error("Err: ", err);
}
const image = "sira-http-proxy";
shell.exec(`docker image rm ${image} -f`)
shell.exec(`docker container stop sira-proxy`);
shell.exec(`docker container rm sira-proxy`);
shell.exec(`docker image build -t ${image} .`);
shell.exec(
`docker container run --name="sira-proxy" -p 10000:20010 -itd ${image} `,
{
async: true,
}
);
}
);


    Dockerfile

FROM node:12.18.4
COPY . /app
WORKDIR /app
RUN npm install
EXPOSE 20010
CMD ["npx", "pm2-runtime", "proxy.js"]


3.3 执行命令

    node shell -t=https://www.tiankele.cn



当前评论 (0) 登录后评论

暂无评论