http反向代理
反向代理(Reverse Proxy)是一种网络通信模式,它充当服务器和客户端之间的中介,将客户端的请求转发到一个或多个后端服务器,并将后端服务器的响应返回给客户端。
用到的库 http-proxy-middleware
npm install http-proxy-middleware
根目录自定义配置文件
zxd.config.js配置:
module.exports = { server: { proxy: { "/api": { target: "http://localhost:3000", changeOrigin: true, }, }, }, };
代理服务:index.js
const http = require("http"); const fs = require("fs"); const url = require("url"); const { createProxyMiddleware } = require("http-proxy-middleware"); const html = fs.readFileSync("./index.html"); const config = require("./zxd.config.js"); http .createServer((req, res) => { const { pathname } = url.parse(req.url, true); const proxyList = Object.keys(config.server.proxy); if (proxyList.includes(pathname)) { const proxy = createProxyMiddleware(config.server.proxy[pathname]); proxy(req, res, (err) => { if (err) { res.statusCode = 500; res.end("Proxy error"); } }); return; } res.writeHead(200, { "Content-Type": "text/html" }); res.end(html); }) .listen(8074, () => { console.log("Server running on http://localhost:8074"); });
服务test.js
const http = require("http"); const url = require("url"); const fs = require("fs"); http .createServer((req, res) => { const { pathname } = url.parse(req.url); console.log(pathname, "??"); if (pathname == "/api") { res.end("proxy success"); } }) .listen(3000, () => { console.log("server is running"); });
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <h1>hello world</h1> </div> <script> fetch('/api').then(res => { return res.text() }).then(res=>{ console.log(res) }) </script> </body> </html>