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

Express路由404错误:访问localhost:3030/staff返回Cannot GET /staff

解决Express路由404问题:Cannot GET /staff

嘿,我帮你找到了问题的根源,这其实是个很容易犯的小错误!

核心问题:路由挂载路径格式错误

在你的app.js里,挂载staff路由的时候写了:

app.use('./staff', staffRouter);

这里的路径不应该带.!Express的路由挂载路径需要是绝对路径格式,也就是直接写/staff,而不是相对路径的./staff。当你用./staff时,Express无法正确解析这个路径,自然匹配不到你访问的localhost:3030/staff,所以返回404错误。

次要问题:静态文件路径拼接错误

另外,你的静态文件服务路径也有小问题:

app.use('/static', express.static(__dirname + './public'));

__dirname本身已经是项目根目录的绝对路径,加上./public会生成类似/your/project/path./public的错误路径,正确的写法应该是:

app.use('/static', express.static(__dirname + '/public'));
// 或者更规范的方式(需要先引入path模块)
// const path = require('path');
// app.use('/static', express.static(path.join(__dirname, 'public')));

修正后的完整app.js代码

const express = require('express');
const app = express();
const port = process.env.PORT || 3030;
const staffRouter = require('./routes/staffrouter.js');

// 修正静态文件路径
app.use('/static', express.static(__dirname + '/public'));
// 修正路由挂载路径
app.use('/staff', staffRouter);

app.get('/', function(req, res) {
  res.render('index.pug');
});

app.listen(port);

额外优化建议

你的staffrouter.js里有一行:

res.render('../views/staff.pug', { ... });

如果你的Express默认配置了views目录(默认就是项目根目录下的views文件夹),可以简化成:

res.render('staff.pug', { ... });

这样写法更简洁规范,也避免了相对路径可能带来的问题。

现在重启你的Express服务,再访问localhost:3030/staff,应该就能正常加载页面啦!

内容的提问来源于stack exchange,提问作者Cuckoo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:32:59