
后端API网关【免费下载链接】http-proxy-middleware:zap: The one-liner node.js http-proxy (httpxy) middleware for connect, express, next.js and more项目地址https://gitcode.com/gh_mirrors/ht/http-proxy-middleware点击查看免费下载本文围绕http-proxy-middleware仓库中的 examples/README.md 展开系统讲解如何一键安装依赖并运行内置示例以及 connect、express、next.js、hono、fastify、browser-sync、WebSocket 等多种服务器场景下的最小可用配置。读完本文你将掌握createProxyMiddleware在主流 Node.js 服务框架中的接入方式、ws升级代理、pathFilter/pathRewrite等核心选项的实战写法并能快速把示例改造成自己的代理方案。示例仓库概述一份代码多框架复用examples目录的核心设计理念是同一份createProxyMiddleware配置在不同服务器框架中以各自惯用的方式挂载。仓库为每个服务器准备了独立的入口文件覆盖了从零依赖的原生node:http到现代边缘框架 hono 的完整生态具体包括browser-sync以中间件形式注入 browser-sync 的静态服务器connectConnect 中间件栈expressExpress 应用fastify通过fastify/express桥接使用hono使用独立的createHonoProxyMiddlewarehttp-server直接作为http.createServer的请求处理器next-appNext.js Pages Router API 路由websocket带ws: true的 WebSocket 代理 浏览器演示页sseServer-Sent Events 流式代理response-interceptor响应拦截与改写含压缩内容处理所有示例都通过examples/package.json中声明的imports字段引用仓库构建产物而不是直接拷贝源码保证了示例与当前版本代码始终同步。环境准备与依赖安装http-proxy-middleware仓库使用 yarn 作为包管理工具并在根 package.json 中提供了两个关键脚本见scripts字段# install:all —— 先安装根目录依赖再进入 examples 目录安装示例依赖 yarn (cd examples yarn) # build —— 通过 tsc --build 将 src 编译到 dist tsc --build在克隆仓库后按 examples/README.md 的指引依次执行yarn install:all yarn buildinstall:all会同时安装根目录包含httpxy、debug、is-glob、micromatch等运行时依赖和examples目录包含browser-sync、connect、express、fastify、fastify/express等 devDependencies见 examples/package.json。build是运行示例的前置条件所有示例都通过#http-proxy-middleware这类子路径导入指向dist下的构建产物未执行构建会导致导入失败。运行示例从根目录一行命令启动所有示例统一约定监听3000端口从仓库根目录直接以node examples/name方式启动命令本身不带.js后缀node examples/browser-syncnode examples/connectnode examples/expressnode examples/websocket大部分示例connect、express、websocket、hono、http-server、sse、response-interceptor 等在启动后会调用open(http://localhost:3000/...)自动打开浏览器并监听SIGINT/SIGTERM信号做优雅关闭调用server.close()。例如 connect 示例的收尾逻辑是process.on(SIGINT, () server.close()); process.on(SIGTERM, () server.close());下面逐个剖析各示例的实现要点。原生 node:http零框架依赖的代理examples/http-server/index.js 展示了最精简的用法——createProxyMiddleware返回的函数本身就兼容 Node.js 请求监听器的签名因此可以直接传给http.createServerimport * as http from node:http; import open from open; import { createProxyMiddleware } from #http-proxy-middleware; const jsonPlaceholderProxy createProxyMiddleware({ target: http://jsonplaceholder.typicode.com, changeOrigin: true, // for vhosted sites, changes host header to match to targets host logger: console, }); const server http.createServer(jsonPlaceholderProxy); server.listen(3000);这里有两个值得注意的选项changeOrigin: true对于基于域名的虚拟主机name-based virtual host场景把请求的Host头改写为目标主机避免目标站点因 Host 不匹配返回错误logger: console将中间件内部日志输出到控制台便于排查转发链路。recipes/servers.md中给出的原生写法与本示例完全一致唯一区别是recipes从已安装的 npm 包导入http-proxy-middleware而examples通过 subpath shim 导入仓库自身的dist产物。Express最经典的挂载方式examples/express/index.js 与 connect 示例共享同一套配置模式二者的核心都是app.use(/users, proxy)import express from express; import open from open; import { createProxyMiddleware } from #http-proxy-middleware; const jsonPlaceholderProxy createProxyMiddleware({ target: http://jsonplaceholder.typicode.com/users, changeOrigin: true, logger: console, }); const app express(); app.use(/users, jsonPlaceholderProxy); const server app.listen(3000);要点app.use(/users, ...)只拦截/users前缀路径其余请求正常走 Express 路由代理目标target直接指向http://jsonplaceholder.typicode.com/users因此本地请求/users会被原样转发到该地址。connect 示例examples/connect/index.js用法几乎相同只是把express()换成connect()、用http.createServer(app)监听const app connect(); app.use(/users, jsonPlaceholderProxy); const server http.createServer(app).listen(3000);对于 connect 来说中间件天然就是其核心抽象createProxyMiddleware返回的标准(req, res, next)函数可直接接入中间件链。Browser-Sync代理作为静态服务器中间件examples/browser-sync/index.js 演示了开发工具链集成把代理中间件放进 browser-sync 的server.middleware数组即可在本地静态页面里直接请求被代理的远程 API。import browserSync from browser-sync; import { createProxyMiddleware } from #http-proxy-middleware; const app browserSync.create(); const jsonPlaceholderProxy createProxyMiddleware({ target: http://jsonplaceholder.typicode.com, pathFilter: /users, // 仅转发 /users 路径 changeOrigin: true, logger: console, }); app.init({ server: { baseDir: ./, // 静态文件根目录 middleware: [jsonPlaceholderProxy], }, port: 3000, startPath: /users, // 启动后自动打开 /users });此处首次出现pathFilter选项它限定只有匹配/users的请求才进入代理其他请求交给 browser-sync 的静态文件服务——这正是前端开发中页面本地化、接口远程化的典型形态。Fastify通过 fastify/express 桥接Fastify 本身是 schema 驱动的框架中间件模型与 Connect 系不同。仓库给出的方案examples/fastify/index.js是先注册fastify/express插件再用fastify.use()挂载代理import fastifyExpress from fastify/express; import fastifyFactory from fastify; import { createProxyMiddleware } from #http-proxy-middleware; const fastify fastifyFactory({ logger: true }); await fastify.register(fastifyExpress); const proxy createProxyMiddleware({ target: http://jsonplaceholder.typicode.com, changeOrigin: true, }); fastify.use(proxy); const address await fastify.listen({ host: 127.0.0.1, port: 3000 }); fastify.log.info(server listening on ${address});注意该示例监听127.0.0.1而非默认的0.0.0.0这是 Fastify 的默认行为差异。recipes/servers.md中提供了同等的异步 IIFE 版本写法两者等价。Hono独立的 createHonoProxyMiddleware 入口Hono 拥有自己的中间件签名仓库为此提供了专门入口。示例 examples/hono/index.js 从#http-proxy-middleware/hono导入createHonoProxyMiddlewareimport { serve } from hono/node-server; import { Hono } from hono; import open from open; import { createHonoProxyMiddleware } from #http-proxy-middleware/hono; const app new Hono(); app.use( /users, createHonoProxyMiddleware({ target: http://jsonplaceholder.typicode.com, changeOrigin: true, logger: console, }), ); const server serve(app);配置项与createProxyMiddleware一致但返回的是 Hono 兼容的处理器。这个独立入口说明http-proxy-middleware对不同框架提供了类型安全的适配层而非要求框架强行兼容 Connect 签名。WebSocket 代理ws 选项与 upgrade 事件examples/websocket/index.js 是理解 WebSocket 代理的完整范例核心是ws: true选项const wsProxy createProxyMiddleware({ target: https://echo.websocket.org, // pathRewrite: { // ^/websocket: /socket, // rewrite path. // ^/removepath: , // remove path. // }, changeOrigin: true, ws: true, // enable websocket proxy logger: console, }); const app express(); app.use(/, express.static(currentDir)); // demo page app.use(wsProxy); const server app.listen(3000); server.on(upgrade, wsProxy.upgrade); // optional: upgrade externally两个关键点ws: true让中间件同时处理 HTTP 与 WebSocket 升级请求。代码注释中还保留了pathRewrite的示例可用于改写 WebSocket 路径前缀。server.on(upgrade, wsProxy.upgrade)WebSocket 握手走的是 HTTPupgrade事件而非普通请求处理这里显式将升级事件转发给代理。注释标注为 optional表明中间件内部也会处理升级但显式注册在需要精细控制升级流程如先做鉴权再放行时更可靠。该目录还附带浏览器端演示页 examples/websocket/index.html页面会依据当前地址自动推导ws://或wss://协议并提供 connect / send / disconnect 三个操作按钮把收发消息实时打印到日志区。验证方式为浏览器打开http://localhost:3000在控制台执行new WebSocket(ws://localhost:3000)后socket.send(hello world)来自echo.websocket.org的服务器回显即证明代理链路畅通。进阶示例SSE 与响应拦截除基础代理外examples 还覆盖两个进阶场景。SSE 流式代理examples/sse/index.js 把https://sse.dev/test作为目标挂载在/test路径下const sseProxy createProxyMiddleware({ target: https://sse.dev/test, changeOrigin: true, logger: console, }); app.use(/test, sseProxy);SSE 本质是长连接流式响应代理中间件只需保证字节流不被打断即可透传无需额外配置——这也侧面说明httpxy底层对响应流的处理是透明转发。response-interceptor改写上游响应examples/response-interceptor/index.js 展示了responseInterceptor与selfHandleResponse: true的配合使用实现请求仍走代理、但响应内容由本地生成的能力const jsonPlaceholderProxy createProxyMiddleware({ target: http://jsonplaceholder.typicode.com, router: { /users: http://jsonplaceholder.typicode.com, /brotli: http://httpbin.org, /gzip: http://httpbin.org, /deflate: http://httpbin.org, }, changeOrigin: true, selfHandleResponse: true, // 手动调用 res.end() on: { proxyRes: responseInterceptor(async (buffer, proxyRes, req, res) { res.setHeader(content-type, application/json; charsetutf-8); res.statusCode 418; return JSON.stringify(favoriteFoods); // 返回完全不同的响应体 }), }, logger: console, });其中router对象实现按路径分发到不同上游目标selfHandleResponse: true告诉中间件响应由我自行处理随后必须在proxyRes事件里调用res.end()responseInterceptor内部会完成拦截回调中可修改响应头、状态码并直接返回新的响应体字符串示例中的favoriteFoods数组特意包含中文、泰文等多字节字符用于验证编码处理。Next.js Pages RouterAPI 路由代理Next.js 示例不通过命令行直接启动而是作为独立应用运行。它由两个文件构成详见 examples/next-app/PROXY.mdexamples/next-app/pages/api/_proxy.ts以单例形式创建代理注释明确说明prevent a new proxy being created for every request避免每个请求重复初始化import type { NextApiRequest, NextApiResponse } from next; import { createProxyMiddleware } from ../../../../dist; // Singleton export const proxyMiddleware createProxyMiddlewareNextApiRequest, NextApiResponse({ target: http://jsonplaceholder.typicode.com, changeOrigin: true, pathRewrite: { ^/api/users: /users, }, logger: console, });examples/next-app/pages/api/users.ts暴露 API 路由并把请求交给单例代理同时通过config.api声明运行时行为import type { NextApiRequest, NextApiResponse, PageConfig } from next; import { proxyMiddleware } from ./_proxy; export default async function handler(req: NextApiRequest, res: NextApiResponse) { return proxyMiddleware(req, res, (result: unknown) { if (result instanceof Error) { throw result; } }); } export const config: PageConfig { api: { externalResolver: true, // 告知 Next.js 响应由代理外部处理 // bodyParser: false, // POST/PUT/PATCH 需透传原始请求体时取消注释 }, };配置要点api.externalResolver true让 Next.js 知道响应由中间件而非路由处理器写回当被代理的POST/PUT/PATCH请求需要原始请求体流时还需设置api.bodyParser false示例中以注释形式保留对应已知的 stalled POST 问题修复方案。pathRewrite把本地/api/users改写为上游/users从而对前端隐藏真实路径。启动与验证在examples/next-app目录下npm run dev # 浏览器打开或 curl 验证 curl http://localhost:3000/api/users若代理配置正确返回内容应来自jsonplaceholder.typicode.com的/users接口。依赖加载机制subpath shim 的作用细心的读者会发现示例导入路径写的是#http-proxy-middleware而非相对路径../../dist/index.js。这一机制由 examples/package.json 的imports字段与 examples/subpath.shim.js 共同实现imports: { #http-proxy-middleware: ./subpath.shim.js, #http-proxy-middleware/hono: ./subpath.hono.shim.js }subpath.shim.js的注释解释了原因Node.js 的 subpath imports 会查找最近的package.json而从上级目录的dist直接导入不被允许因此需要一个 shim 从父级../dist/index.js重新导出export * from ../dist/index.js;这样示例代码就能以语义化的#http-proxy-middleware导入仓库构建产物既避免了冗长的相对路径也确保了示例永远指向当前源码编译出的最新版本。更多服务器实现recipes/servers.md 总览examples/README.md 末尾将读者导向 recipes/servers.md那里汇总了更完整的服务器兼容清单除 examples 已覆盖的之外还包括Polka轻量框架直接app.use(proxy)lite-server在bs-config.mjs中通过server.middleware的键位10注入注释说明从键 10 开始是为了不覆盖 lite-server 自带的默认中间件grunt-contrib-connect支持以Array直接传middleware: [apiProxy]也支持以function(connect, options, middlewares)形式用middlewares.unshift(apiProxy)注入gulp-connect在connect.server({ middleware: fn })回调里返回[apiProxy]grunt-browser-syncserver.baseDirmiddleware: apiProxygulp-webserver配合livereload、directoryListing使用这些示例普遍复用pathFilter: /apichangeOrigin: true的组合说明该配置对多数仅代理特定路径的场景都适用可直接作为模板迁移到任意 Connect 兼容的中间件宿主。实战总结与故障排查提示综合全部示例可以归纳出http-proxy-middleware在多服务器场景下的通用接入模式创建代理createProxyMiddleware({ target, changeOrigin, ... })返回标准中间件函数挂载方式Connect 系用app.use(path, proxy)原生 HTTP 用http.createServer(proxy)Hono 用createHonoProxyMiddlewareFastify 需先注册fastify/express路径控制pathFilter限定代理范围pathRewrite改写转发路径router按路径分发多目标WebSocket加ws: true必要时监听upgrade事件并调用proxy.upgrade响应定制selfHandleResponse: trueon.proxyResresponseInterceptor调试统一配置logger: console观察请求转发细节。常见问题定位思路若本地请求未命中代理优先检查pathFilter/app.use的路径前缀是否一致若目标站点返回异常先确认changeOrigin是否开启若 WebSocket 连不上确认ws: true与upgrade事件转发均已配置。这些判断依据均可在本仓库 examples 目录的对应实现中找到直接佐证。赞分享后端API网关【免费下载链接】http-proxy-middleware:zap: The one-liner node.js http-proxy (httpxy) middleware for connect, express, next.js and more项目地址https://gitcode.com/gh_mirrors/ht/http-proxy-middleware点击查看免费下载相关推荐http-proxy-middleware 多服务器接入实战从 http.createServer 到 Express、Next.js 的一行代理集成指南http proxy middleware 多服务器接入实战从 http.createServer 到 Express、Next.js 的一行代理集成指南 h后端API网关YimMenu终极指南5个步骤掌握GTA5最强开源菜单工具YimMenu终极指南5个步骤掌握GTA5最强开源菜单工具 YimMenu是一款专为GTA5在线模式设计的开源辅助工具它不仅提供了丰富的游戏功能增强更重要逆向工程游戏开发创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考