Express.js用Postman测试时遇connect ECONNREFUSED 127.0.0.1:8000错误求助
排查Postman请求MongoDB连接时的ECONNREFUSED 127.0.0.1:8000错误
我是行业新手,在尝试通过Postman发送API请求检查MongoDB数据库连接时,出现了Error: connect ECONNREFUSED 127.0.0.1:8000错误。跟着教程操作但无法定位问题,恳请帮忙找出错误。
我的代码
const app = express(); const { MongoClient } = require('mongodb'); const PORT = process.env.PORT || 8000; // Initialize middleware // we used to install body parser but now it's a built in middleware // Function of express. It parses incoming JSONpayload // app.use(express.json({extended:false})); app.use(express.json({ extended: false })); // Test Routs // app.get("/", (req,res)=>res.send("Hello Aruna !!!")); // app.post("/", (req,res)=>res.send(`Hello ${req.body.name} `)); // app.get("/hello/:name", (req.res)=>res.send(`Hello ${req.params.name}`)) app.get('/api/articles/:name', async (req, res) => { try { const articleName = req.params.name; const client = await MongoClient.connect('mongodb://localhost:27017'); const db = client.db('mernblog'); const articlesinfo = db .collection('articles') .findOne({ name: articleName }); res.status(200).jason(articlesinfo); client.close(); } catch (error) { res.status(500).jason({ message: 'Error connecting to database', error }); } }); app.post('/api/articles/:name/add-comments', (req, res) => { const { username, text } = req.body; const articleName = req.params.name; articlesinfo[articleName].comments.push({ username, text }); res.status(200).send(articlesinfo[articleName]); }); app.post('/', (req, res) => res.send(`Hello ${req.body.name}`)); app.get('/hello/:name', (req, res) => res.send(`Hello ${req.params.name}`)); app.listen(PORT, () => console.log(`Server is running at port ${PORT}`));
相关截图说明
- Server.js 文件截图
- 终端运行截图
- Postman中API请求及错误截图
问题排查与解决方案
1. 先解决服务启动失败的核心问题
ECONNREFUSED错误本质是Postman连不上8000端口的服务,大概率是你的Node.js服务没正常启动,代码里有语法/逻辑错误:
- 缺少express导入:代码第一行
const app = express();但没导入express模块,必须添加const express = require('express');,否则启动时会抛出ReferenceError: express is not defined。 res.jason拼写错误:所有res.status(xxx).jason(...)里的jason都是拼写错误,正确写法是res.json(),这个错误会导致接口调用时抛出异常,直接让服务崩溃。- 异步函数未加await:
db.collection('articles').findOne(...)是异步操作,必须加await才能获取实际查询结果,否则articlesinfo只是一个Promise对象,无法正确返回数据。 - 未定义变量直接使用:
post /api/articles/:name/add-comments路由里直接使用articlesinfo变量,但这个变量只在get路由的作用域里定义,全局未声明,会抛出ReferenceError: articlesinfo is not defined,导致服务启动失败。
2. MongoDB连接与数据操作修正
- 确保MongoDB本地服务启动:检查本地MongoDB是否正常运行(默认端口27017),可以通过终端执行
mongod命令启动,或者查看系统服务中的MongoDB状态。 - 添加连接选项:
MongoClient.connect建议添加兼容性选项,避免版本差异导致的连接问题:const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true, useUnifiedTopology: true }); - 修正评论添加逻辑:原代码直接操作内存变量,应该改为操作MongoDB数据库,确保数据持久化。
3. Postman请求验证
- 确认请求URL为
http://localhost:8000/api/articles/[你的文章名称](替换实际文章名称),端口和路径无误。 - POST请求需在Body中选择
raw-JSON格式,传入正确的参数,比如:{ "username": "test", "text": "这是一条测试评论" }
修正后的完整代码
const express = require('express'); const app = express(); const { MongoClient } = require('mongodb'); const PORT = process.env.PORT || 8000; // 初始化中间件 app.use(express.json({ extended: false })); app.get('/api/articles/:name', async (req, res) => { try { const articleName = req.params.name; // 添加连接选项,避免版本兼容问题 const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true, useUnifiedTopology: true }); const db = client.db('mernblog'); // 加await获取实际查询结果 const articleInfo = await db.collection('articles').findOne({ name: articleName }); // 修正拼写错误为res.json res.status(200).json(articleInfo); client.close(); } catch (error) { res.status(500).json({ message: 'Error connecting to database', error: error.message }); } }); app.post('/api/articles/:name/add-comments', async (req, res) => { const { username, text } = req.body; const articleName = req.params.name; try { const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true, useUnifiedTopology: true }); const db = client.db('mernblog'); // 更新数据库中的评论 await db.collection('articles').updateOne( { name: articleName }, { $push: { comments: { username, text } } } ); // 获取更新后的文章信息 const updatedArticle = await db.collection('articles').findOne({ name: articleName }); res.status(200).json(updatedArticle); client.close(); } catch (error) { res.status(500).json({ message: 'Error updating comments', error: error.message }); } }); app.post('/', (req, res) => res.send(`Hello ${req.body.name}`)); app.get('/hello/:name', (req, res) => res.send(`Hello ${req.params.name}`)); app.listen(PORT, () => console.log(`Server is running at port ${PORT}`));
内容的提问来源于stack exchange,提问作者Mangala Karunarathne
相关产品推荐
相关产品推荐

