http实现反向代理

http实现反向代理
  • 需要安装http-proxy-middleware插件
js 复制代码
npm i http-proxy-middleware
  • 准备proxy.html, 等会加载proxy.html可直接发起fetch请求
js 复制代码
<!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 发起接口请求
      fetch("/api").then((res) => res.text());
    </script>
  </body>
</html>
  • 准备xxx.config.js配置文件,配置proxy代理
js 复制代码
module.exports = {
  serve: {
    proxy: {
      "/api": {
        target: "http://localhost:3000",  // 代理端口号到3000
        changeOrigin: true,
        rewrite:'相应的正则替换', // 可写可不写
      },
    },
  },
};
  • 准备proxyTest.js 代理node服务,服务端口号为3000
js 复制代码
const http = require("node:http");
const url = require("node:url");

http
  .createServer((req, res) => {
    // 接口路径带api的,则拦截提示返回成功 
    const { pathname } = url.parse(req.url);
    if (pathname === "/api") {
      res.end("代理 3000 成功");
    }
  })
  .listen(3000, () => {
    console.log("启动3000服务");
  });
  • 准备proxy.js 文件
js 复制代码
const fs = require("node:fs");
const http = require("node:http");
const url = require("node:url");
// 反向代理中间代码
const { createProxyMiddleware } = require("http-proxy-middleware");

// 获取html的内容,启动服务后可直接加载发起接口请求
const html = fs.readFileSync("./proxy.html");

// 获取配置文件里的serve配置内容
const config = require("./xxx.config.js");

http
  .createServer((req, res) => {
    // 获取url接口端口号后面的名称
    const { pathname } = url.parse(req.url);
    // 获取配置文件中的 配置 如 /api
    const proxyList = Object.keys(config.serve.proxy);

    // 若是请求的接口中包含代理配置的内容,进行反向代理
    if (proxyList.includes(pathname)) {
      const proxy = createProxyMiddleware(config.serve.proxy[pathname]);
      // 进行代理
      proxy(req, res);
      return;
    }
    // 把html内容与服务整合在一起
    res.writeHead(200, {
      "Content-Type": "text/html",
    });
    res.end(html);
  })
  .listen(8080, () => {
    console.log("启动了一个80服务");
  });
nodejs反向代理基本实现思路如上
相关推荐
LCG元9 小时前
STM32实战:基于STM32F103的4G模块(EC20)HTTP通信
stm32·嵌入式硬件·http
TechWayfarer10 小时前
IP归属地API 技术解析与应用实践
网络·网络协议·tcp/ip
河阿里11 小时前
JWT 与 Cookie/Session 的对比分析
网络协议
饺子不吃醋12 小时前
深入理解HTTP:请求/响应、缓存机制、登录态与跨域
http
路由侠内网穿透.12 小时前
本地部署开源客服系统 FreeScout 并实现外部访问( Windows 版本)
运维·服务器·网络·windows·网络协议
你觉得脆皮鸡好吃吗13 小时前
Check Anti-CSRF Token (AI)
前端·网络·网络协议·安全·csrf·网络安全学习
小p13 小时前
nestjs 学习17:封装一个微服务注册与配置中心的动态模块
node.js
老王以为13 小时前
深入理解 AbortController:从底层原理到跨语言设计哲学
javascript·设计模式·node.js
渠过客14 小时前
【运维】PM2 使用完全指南:Node.js 应用进程管理利器
运维·node.js
小粉粉hhh16 小时前
Node.js(一)——初始Node.js
node.js