You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+Express框架下Rest API出现Cannot GET /published错误求助

解决Express.js中Cannot GET /published错误

问题根源

你定义了路由规则但没有将路由对象挂载到Express的app实例上,导致Express无法识别/published这个路由。

修复步骤

  1. 修改路由文件
    在路由文件末尾添加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。

  1. 确保主应用文件引入路由模块
    在你的主文件(比如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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:17:42