http实现反向代理
 
- 需要安装http-proxy-middleware插件
 
 
npm i http-proxy-middleware
 
- 准备proxy.html, 等会加载proxy.html可直接发起fetch请求
 
 
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    有内容
    <script>
      
      fetch("/api").then((res) => res.text());
    </script>
  </body>
</html>
 
- 准备xxx.config.js配置文件,配置proxy代理
 
 
module.exports = {
  serve: {
    proxy: {
      "/api": {
        target: "http://localhost:3000",  
        changeOrigin: true,
        rewrite:'相应的正则替换', 
      },
    },
  },
};
 
- 准备proxyTest.js 代理node服务,服务端口号为3000
 
 
const http = require("node:http");
const url = require("node:url");
http
  .createServer((req, res) => {
    
    const { pathname } = url.parse(req.url);
    if (pathname === "/api") {
      res.end("代理 3000 成功");
    }
  })
  .listen(3000, () => {
    console.log("启动3000服务");
  });
 
 
const fs = require("node:fs");
const http = require("node:http");
const url = require("node:url");
const { createProxyMiddleware } = require("http-proxy-middleware");
const html = fs.readFileSync("./proxy.html");
const config = require("./xxx.config.js");
http
  .createServer((req, res) => {
    
    const { pathname } = url.parse(req.url);
    
    const proxyList = Object.keys(config.serve.proxy);
    
    if (proxyList.includes(pathname)) {
      const proxy = createProxyMiddleware(config.serve.proxy[pathname]);
      
      proxy(req, res);
      return;
    }
    
    res.writeHead(200, {
      "Content-Type": "text/html",
    });
    res.end(html);
  })
  .listen(8080, () => {
    console.log("启动了一个80服务");
  });
 
nodejs反向代理基本实现思路如上