求助:Node.js注册接口无法建立cookie session及连接失败问题
先看你终端里的核心报错:
(node:7978) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined at /Users/gabrielswee/Desktop/Desktop Folders/Courses/Javascript/ecomm/index.js:58:29
这个错误直接指向req.session.userId = user.id;这一行——说明你拿到的user是undefined,根本没有获取到新建的用户对象。
核心问题:UsersRepository.create方法未返回用户实例
你的UsersRepository类里的create方法,完成了用户数据写入文件的操作,但没有返回新建的用户记录。当你在路由里调用await usersRepo.create(...)时,得到的结果就是undefined,自然无法读取user.id。
修复create方法
修改user.js中的create方法,最后添加返回语句:
async create(attrs) { attrs.id = this.randomId(); const records = await this.getAll(); records.push(attrs); await this.writeAll(records); // 返回新建的用户对象,这样路由里就能拿到user实例了 return attrs; }
额外优化:处理未捕获的Promise拒绝
终端里的警告提示你存在未处理的Promise拒绝,这在Node.js的新版本中会直接终止进程——这也是你遇到“localhost拒绝连接”的原因:服务器因为未捕获的错误崩溃了。
给你的POST路由加上try/catch块,捕获并处理错误:
app.post("/", async (req, res) => { try { const { email, password, passwordConfirmation } = req.body; const existingUser = await usersRepo.getOneBy({ email }); if (existingUser) { return res.send("Email in use"); } if (password !== passwordConfirmation) { return res.send("Password must match"); } const user = await usersRepo.create({ email, password }); req.session.userId = user.id; res.send("Account Created !!!"); } catch (err) { console.error("Sign up error:", err); res.status(500).send("Oops, something went wrong during sign up"); } });
为什么会出现“localhost拒绝连接”?
当未处理的Promise拒绝发生时,Node.js进程会变得不稳定,严重时会直接退出。你的服务器在报错后停止运行,浏览器自然无法连接到localhost:3000。修复上面的两个问题后,服务器就能稳定处理请求,不会再出现连接失败的情况。
内容的提问来源于stack exchange,提问作者gabswee

