Express服务器特定路由无法访问问题求助
问题
我是Web开发新手,正在搭建一个MERN栈副业项目,遇到以下问题:
能正常访问/api/matches/路由,但访问/api/matches/matchlist/时,Postman报错:
GET http://localhost:4000/api/matches/matchlist Error: connect ECONNREFUSED ::1:3000 Request Headers User-Agent: PostmanRuntime/7.31.1 Accept: */* Postman-Token: fa77215b-eb3c-4667-8b8d-63ffc2bd84be Host: localhost:4000 Accept-Encoding: gzip, deflate, br Connection: keep-alive
同时服务器控制台显示500内部服务器错误。
相关代码如下:
服务器文件(server.js)
const express = require('express'); const connectMongDB = require('./config/connectMongoDB'); // 引入matches路由文件 const matches = require('./routes/matches'); // 连接MongoDB connectMongDB(); const app = express(); app.use(express.json()); const port = process.env.PORT || 4000; // 挂载matches路由到/api/matches路径 app.use('/api/matches', matches); app.listen(port, ()=>{ console.log(`Server is running on port: ${port}`); });
matches路由文件(routes/matches.js)
const express = require('express'); const router = express.Router(); const Match = require('../database_models/matchModel'); // 获取所有赛事 router.get('/', async (req, res) => { //console.log("User is authenticated"); try { const matches = await Match.find(); console.log(matches); res.json(matches); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); // 根据ID获取赛事 router.get('/:id', ensureUserAuthenticated, async (req, res) => { try { const match = await Match.findById(req.params.id); if (!match) { return res.status(404).json({ msg: 'Match not found' }); } res.json(match); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); router.get('/matchlist', (req,res) => { res.send("Success"); }); module.exports = router;
解决方案
核心原因
Express的路由是从上到下匹配的,当访问/api/matches/matchlist时,会先被/:id动态路由匹配——Express会把matchlist当成id参数的值,进入该路由的处理逻辑。而该路由中调用了未定义的ensureUserAuthenticated中间件,导致服务器抛出500错误。
修复步骤
- 调整路由顺序:把具体的
/matchlist路由放到动态/:id路由之前,确保精准路由先被匹配:
// 先定义matchlist路由 router.get('/matchlist', (req,res) => { res.send("Success"); }); // 再定义动态:id路由 router.get('/:id', ensureUserAuthenticated, async (req, res) => { // ... 原有代码 });
- 处理未定义的中间件:
ensureUserAuthenticated函数未在当前文件定义或引入,可二选一处理:- 补充该中间件的认证逻辑实现
- 暂时不需要认证的话,先注释掉该中间件:
router.get('/:id', /* ensureUserAuthenticated, */ async (req, res) => { // ... 原有代码 });
验证修复
修改后重启服务器,再次访问/api/matches/matchlist,应该能正常返回"Success"。
内容的提问来源于stack exchange,提问作者Modern Mahrshi
相关产品推荐
相关产品推荐

