Node.js+Express框架下Rest API出现Cannot GET /published错误求助
解决Express.js中Cannot GET /published错误
问题根源
你定义了路由规则但没有将路由对象挂载到Express的app实例上,导致Express无法识别/published这个路由。
修复步骤
- 修改路由文件
在路由文件末尾添加app.use(),把定义好的router挂载到app上:
module.exports = app => { const tutorials = require("../controllers/tutorial.controller.js"); var router = require("express").Router(); router.get("/published", tutorials.findAllPublished); // 将router挂载到app,这里用根路径作为前缀,也可以自定义前缀比如/api app.use('/', router); };
如果需要给所有路由加统一前缀(比如/api),可以改成:
app.use('/api', router);
此时访问路径会变成/api/published。
- 确保主应用文件引入路由模块
在你的主文件(比如app.js或server.js)中,要引入这个路由模块并传入app实例:
const express = require('express'); const app = express(); // 引入路由文件,路径根据你的实际项目结构调整 require('./routes/tutorial.routes.js')(app); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
验证修复
启动服务后,访问对应的路径:
- 无前缀:
http://localhost:3000/published - 带/api前缀:
http://localhost:3000/api/published
此时应该能收到Hello world的响应。
内容的提问来源于stack exchange,提问作者pamela
相关产品推荐
相关产品推荐

