Node.js 18中Express Router结合http-proxy-middleware使用报错
问题分析与修复
你的代码存在两个核心问题,导致请求http://localhost:6001/api/posts/all时返回Cannot GET /api/posts/all:
Express Router未挂载到主应用
你创建了router并定义了/all路由,但没有将该router挂载到Express主应用的/api/posts路径下,导致应用无法识别/api/posts/all这个端点。代理路径重写规则不匹配
当前pathRewrite规则针对^/api/posts/all,但由于router拦截了/api/posts下的请求,实际传递给代理中间件的路径是/all,该规则无法匹配生效。
修正后的代码
const express = require('express'); const router = express.Router(); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); const PORT = 6001; const HOST = "localhost"; const API_URL = "https://jsonplaceholder.typicode.com"; // 修改为API基础地址,提升灵活性 // 调整代理配置,确保路径重写正确指向目标API const proxyOptions = { target: API_URL, changeOrigin: true, pathRewrite: { [`^/api/posts/all`]: '/posts', // 将请求路径重写为目标API的/posts端点 }, } // 直接在主应用上挂载代理路由(更直观的方式) app.get('/api/posts/all', createProxyMiddleware(proxyOptions)); // 若坚持使用Router,需补充挂载代码: // router.get('/all', createProxyMiddleware({ // target: API_URL, // changeOrigin: true, // pathRewrite: { [`^/all`]: '/posts' } // })); // app.use('/api/posts', router); app.listen(PORT, HOST, () => { console.log(`Proxy Started at ${HOST}:${PORT}`) });
关键修复说明
- 调整API基础地址:将
API_URL改为https://jsonplaceholder.typicode.com,便于通过路径重写精准控制最终请求的API端点。 - 补全路由挂载逻辑:无论是直接在主应用定义路由,还是挂载Router,都要确保应用能接收到
/api/posts/all路径的请求。 - 修正路径重写规则:让重写后的路径正确指向目标API的
/posts端点,确保请求被代理到正确的地址获取数据。
现在访问http://localhost:6001/api/posts/all即可正常返回数据。
内容的提问来源于stack exchange,提问作者user16968394
相关产品推荐
相关产品推荐

