ExpressJS集成http-proxy-middleware代理遇504超时问题排查与解决
Express + http-proxy-middleware 504网关超时问题解决
问题场景
用npx express-generator初始化Express项目后,在routes/index.js中配置http-proxy-middleware,将请求代理到http://jsonplaceholder.typicode.com/users,并在app.js中挂载该路由。启动项目后,通过Postman访问http://localhost:3000/test时出现504网关超时错误,但直接访问http://jsonplaceholder.typicode.com/users能正常返回数据。
解决方案
通过以下两个步骤修复问题:
1. 配置pathRewrite移除请求前缀
代理请求时,原路径/test会被附加到目标API地址后,导致目标服务器无法识别该路径(目标API的正确路径是/users而非/test/users),因此需要添加路径重写规则,移除/test前缀。
修改routes/index.js中的代理配置:
const express = require('express'); const router = express.Router(); const { createProxyMiddleware } = require('http-proxy-middleware'); router.use('/test', createProxyMiddleware({ target: 'http://jsonplaceholder.typicode.com/users', changeOrigin: true, pathRewrite: { '^/test': '' } // 关键:移除/test前缀 })); module.exports = router;
2. 移除Express-generator自动添加的干扰中间件
Express-generator默认生成的app.js中部分中间件会干扰代理请求的处理,需要移除这些中间件。例如默认添加的express.json()、express.urlencoded()或express.static()可能导致请求被提前处理,无法正常转发到代理中间件。
修改app.js,移除以下自动生成的中间件:
// 移除这些可能干扰代理的中间件 // app.use(express.json()); // app.use(express.urlencoded({ extended: false })); // app.use(express.static(path.join(__dirname, 'public')));
完成以上修改后,重启项目,访问http://localhost:3000/test即可正常获取目标API的返回结果。
内容的提问来源于stack exchange,提问作者keylogger
相关产品推荐
相关产品推荐

