使用http-proxy-middleware时,路由不匹配如何执行后续逻辑?
解决http-proxy-middleware不匹配时执行后续路由的问题
你的核心需求是让代理中间件仅处理匹配/api/url1和/api/url2的请求,不匹配的请求直接流转到后续的routerAnotherUrls处理。默认情况下,http-proxy-middleware在找不到匹配代理规则时会直接返回404,不会继续执行后续中间件,可通过以下配置调整:
方法一:使用onNoMatch回调(推荐)
http-proxy-middleware提供了onNoMatch选项,当请求没有匹配到任何代理规则时会触发该回调,你可以在这里调用next()让请求继续向后流转:
const app = express(); // 1st : `/mainUrls/*` 由主应用处理 app.use("/mainUrls", routerMainUrls); // 2nd : 配置代理规则 const proxyTable = { "/api/url1" : "http://localhost:3010", "/api/url2" : "http://localhost:3020", }; const options = { router: proxyTable, // 当无匹配代理规则时,调用next()执行后续中间件 onNoMatch: (req, res, next) => { next(); } }; const myProxy = createProxyMiddleware(options); app.use(myProxy); // 3rd : 处理所有其他URL app.use(routerAnotherUrls);
方法二:使用skip选项过滤请求
通过skip函数判断请求路径是否需要跳过代理,不匹配规则的请求直接跳过代理,进入后续路由:
const pathToRegexp = require('path-to-regexp'); const app = express(); app.use("/mainUrls", routerMainUrls); const proxyTable = { "/api/url1" : "http://localhost:3010", "/api/url2" : "http://localhost:3020", }; // 生成路径匹配器,支持匹配子路径(如/api/url1/detail) const proxyMatchers = Object.keys(proxyTable).map(path => pathToRegexp(path)); const options = { router: proxyTable, // 当请求路径不匹配任何代理规则时,跳过代理 skip: (req) => { const isProxyMatch = proxyMatchers.some(matcher => matcher.test(req.path)); return !isProxyMatch; } }; const myProxy = createProxyMiddleware(options); app.use(myProxy); app.use(routerAnotherUrls);
方法三:自定义router函数
通过自定义router函数返回匹配的代理目标;当无匹配时返回null,结合onNoMatch确保调用后续中间件:
const app = express(); app.use("/mainUrls", routerMainUrls); const proxyTable = { "/api/url1" : "http://localhost:3010", "/api/url2" : "http://localhost:3020", }; const options = { router: (req) => { // 查找是否有匹配的代理路径(支持子路径匹配) const matchedPath = Object.keys(proxyTable).find(path => req.path.startsWith(path)); return matchedPath ? proxyTable[matchedPath] : null; }, onNoMatch: (req, res, next) => { next(); } }; const myProxy = createProxyMiddleware(options); app.use(myProxy); app.use(routerAnotherUrls);
以上三种方法都能实现你的需求,其中方法一最简洁直接,利用官方回调完成流转;方法二更灵活,适合复杂路径判断的场景。
内容的提问来源于stack exchange,提问作者gduh
相关产品推荐
相关产品推荐

