Express.js路由连接失败求助:API无响应返回‘not connected’
路由连接API无响应,返回"not connected"错误排查
问题描述
调用API时无响应,返回状态错误信息"not connected",相关代码文件如下:
restaurants.route.js(路由集成文件)
import express from "express" const router = express.Router() router.route('/api/v1/restaurants').get((req,res) => res.send("helloworld")) export default router
index.js(MongoDB连接文件)
import mongodb from "mongodb" import dotenv from "dotenv" dotenv.config() const MongoClient = mongodb.MongoClient const port = process.env.PORT || 8000 MongoClient.connect( process.env.RESTREVIEWS_DB_URI, { maxPoolSize: 50, wtimeoutMS: 2500, useNewUrlParser: true, } ) .catch(err =>{ console.error(err.stack) process.exit(1) }) .then(async client =>{ App.listen(port,() =>{ console.log(`listen on port ${port}`) }) })
server.js(服务器连接文件)
import express from "express"; import cors from "cors"; import restaurants from "./api/restaurants.route.js" const App = express() App.use(cors()) App.use(express.json()) App.use("/api/v1/restaurants", restaurants) App.use("*", (req, res) => res.status(404).json({error:"not connected"})) export default App
问题原因及修复方案
1. 路由路径重复挂载
server.js已将路由挂载到/api/v1/restaurants路径,但restaurants.route.js的路由又定义了完整的/api/v1/restaurants路径,导致实际访问路径变为/api/v1/restaurants/api/v1/restaurants,无法匹配到正确路由,触发404的"not connected"错误。
修复:
修改restaurants.route.js,使用相对路径:
import express from "express" const router = express.Router() router.route('/').get((req,res) => res.send("helloworld")) export default router
2. index.js未导入App实例
index.js中直接调用App.listen(),但未从server.js导入App,会导致App未定义,服务器无法正常启动。
修复:
在index.js顶部添加导入语句:
import App from "./server.js"
3. 可选优化:完善MongoDB连接逻辑
MongoDB连接成功后,可将数据库实例挂载到App对象,方便后续路由调用:
.then(async client =>{ App.locals.db = client.db(process.env.RESTREVIEWS_DB_NAME) App.listen(port,() =>{ console.log(`listen on port ${port}`) }) })
内容的提问来源于stack exchange,提问作者Narayana
相关产品推荐
相关产品推荐

