http实现反向代理

本文介绍了如何在Node.js环境中使用http-proxy-middleware插件实现HTTP反向代理,包括创建proxy.html、配置proxy.config.js以及处理proxyTest.js中的服务端。通过设置代理,可以将请求转发到其他服务器,简化API访问过程。
摘要由CSDN通过智能技术生成
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 发起接口请求
      fetch("/api").then((res) => res.text());
    </script>
  </body>
</html>
  • 准备xxx.config.js配置文件,配置proxy代理
module.exports = {
  serve: {
    proxy: {
      "/api": {
        target: "http://localhost:3000",  // 代理端口号到3000
        changeOrigin: true,
        rewrite:'相应的正则替换', // 可写可不写
      },
    },
  },
};

  • 准备proxyTest.js 代理node服务,服务端口号为3000
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 文件
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反向代理基本实现思路如上
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值