Serverless Offline与Express路由异常:无法调用第二个路由求助
解决Express路由总是触发第一条的问题
看起来你的代码本身逻辑是没问题的,之所以第二条路由/test没被触发,大概率是Serverless部署的路径配置问题(因为你用到了serverless-http),下面一步步帮你排查解决:
1. 先本地验证代码是否正常
首先排除代码本身的问题,给你的代码加上本地监听端口,直接运行测试:
const express = require('express'); const serverless = require('serverless-http'); const app = express() // 第一条路由 app.get('/', function (req, res) { res.send('Hello World!') }) // 第二条路由 app.get('/test', function (req, res) { res.send('Hello Test!') }) // 新增本地监听代码 app.listen(3000, () => { console.log('本地服务启动:http://localhost:3000'); }); module.exports.handler = serverless(app);
运行node index.js,然后访问http://localhost:3000/test,如果能正常返回Hello Test!,说明代码逻辑完全没问题,问题出在Serverless平台的部署配置上。
2. 检查Serverless平台的路径转发配置
因为你用了serverless-http,通常是部署在AWS Lambda、Netlify、Vercel这类Serverless平台,这类平台需要配置让所有子路径的请求都转发到你的Express Handler,否则只有根路径/的请求会被处理,其他路径会被拦截或者错误映射到根路由。
举几个常见平台的配置示例:
- Serverless Framework(AWS Lambda)
在serverless.yml的函数事件配置里,必须加上/{proxy+}来匹配所有子路径:
functions: app: handler: index.handler events: - http: ANY / - http: ANY /{proxy+} # 关键:匹配所有子路径请求
- Vercel
在项目根目录创建vercel.json,配置路径重写:
{ "rewrites": [ { "source": "/(.*)", "destination": "/index.js" } ] }
- Netlify
在netlify.toml里配置重写规则:
[[redirects]] from = "/*" to = "/.netlify/functions/index" # 你的handler路径 status = 200
3. 处理部署后的路径前缀问题
有些平台部署后,你的服务会有固定前缀(比如/api或者/.netlify/functions/index),这时候你需要调整路由或者配置serverless-http的basePath:
方法一:配置basePath
初始化serverless-http时指定你的服务前缀:
module.exports.handler = serverless(app, { basePath: '/api' });
方法二:用Router挂载前缀
用Express的Router来统一管理路由,挂载到对应前缀:
const express = require('express'); const serverless = require('serverless-http'); const app = express() const router = express.Router(); // 把路由都挂载到router上 router.get('/', (req, res) => res.send('Hello World!')); router.get('/test', (req, res) => res.send('Hello Test!')); // 假设部署后的前缀是/api app.use('/api', router); module.exports.handler = serverless(app);
这样访问/api/test就能正确触发第二条路由了。
内容的提问来源于stack exchange,提问作者taufiq
相关产品推荐
相关产品推荐

