Mongoose与MongoDB存用户失败:Postman请求无响应排查求助
问题排查与修复方案
Hey, let's dig into why your POST request is failing with that "socket hang up" error. I spotted a few critical issues in your code that are almost certainly the cause:
1. MongoDB连接字符串缺失引号
在你的服务器代码里,mongoose.connect的连接字符串没有用引号包裹,这会直接导致Node.js抛出语法错误,服务器甚至无法正常启动:
// 错误写法 mongoose.connect(mongodb://localhost/users, { useUnifiedTopology: true, useNewUrlParser: true }, () => console.log("connected!")) // 修复后 mongoose.connect('mongodb://localhost/users', { useUnifiedTopology: true, useNewUrlParser: true }, () => console.log("connected!"))
注意:字符串类型的参数必须用单引号或双引号包裹,否则Node会把它识别为未定义的变量。
2. 路由文件缺少必要的导入与导出
你的routes/aouth.js文件存在三个关键遗漏:
- 没有导入Express的Router对象
- 没有导入User模型
- 没有导出定义好的路由
修复后的完整路由代码:
const express = require('express'); const router = express.Router(); // 导入User模型,路径根据你的文件结构调整(如果User.js和routes文件夹同级,就用../User) const User = require('../User'); router.post('/reg', async(req, res) => { const user = new User({ password: req.body.password }) try { const savedUser = await user.save() res.status(201).json(savedUser) } catch (err) { res.status(400).json({ message: err.message }) } }) // 必须导出router,否则主服务器无法识别路由 module.exports = router;
3. 验证服务器启动状态
修复完代码后,重启服务器,一定要检查控制台输出:
- 确认看到
listening on port 3000!,说明服务器正常启动 - 确认看到
connected!,说明MongoDB连接成功
测试修复效果
用Postman重新发送请求时,确保:
- 请求方法是POST,URL为
http://localhost:3000/api/user/reg - 请求体选择
raw->JSON格式,内容为:
{"password":"1234"}
这样应该就能正常保存用户并返回响应了。
内容的提问来源于stack exchange,提问作者Shir Cohen
相关产品推荐
相关产品推荐

