尝试使用bcrypt设置登录api时出现NextJS和mongose错误



我目前正在尝试设置一个端点,该端点首先检查用户是否存在,然后将输入的密码与存储在MongoDB数据库中的哈希密码进行比较。我使用NextJS、Mongoose和Bcrypt来实现这一点。用户模型包含一个比较密码的函数。它看起来像这样:

UserSchema.methods.comparePassword = function(candidatePassword: string, cb: any) {
bcrypt.compare(candidatePassword, this.password, function(err: any, isMatch: any) {
if (err) return cb(err);
cb(null, isMatch);
});
};

在登录api上,我调用函数并将输入的密码与数据库中的密码进行比较。一切都按计划进行,同时返回适当的JSON res和消息,但每当我向端点发送请求时,我都会收到一个错误,说API resolved without sending a response for /api/login, this may result in stalled requests.。这是我用于登录端点的代码:

import dbConnect from "../../lib/dbConnect";
import User from "../../models/User"
import type { NextApiRequest, NextApiResponse } from 'next'
//installed passportjs for auth
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
await dbConnect()
//type of request
const {method} = req
if (method === "POST") {
try {
const user = await User.findOne({email: req.body.email}); 
//checks if user does not exist
if (!user) {
res.status(400).json({error: "email not found"})
}
//if user exists: check password
user.comparePassword(req.body.password, function(err, isMatch) {
if (isMatch && !err) {
res.status(200).json({success: "password matches"})
}
else {
res.status(400).json({error: "password does not match"})
}
})

} catch (error) {
res.status(400).json({error: "connection error"})
}
}
}
API resolved without sending a response for

这意味着路由处理程序在没有响应的情况下完成。

你要么return每个res.status

return res.status(200).json({success: "password matches"})

或者以结束

res.status(200).json({success: "password matches"})
res.end()

如果这些不起作用,请转换为async/await语法:

userSchema.methods.comparePassword = async function (candidatePassword) {
return await bcrypt.compare(candidatePassword, this.password);
};

在处理程序功能中

try{
const user = await User.findOne({email: req.body.email}); 
//checks if user does not exist
if (!user) {
return res.status(400).json({error: "email not found"})
}

const isPasswordMatched = await user.comparePassword(req.body.password);
if (!isPasswordMatched) {
throw new Error("please enter email or password");
}
res.status(200).json({success: "password matches"})
}

相关内容

  • 没有找到相关文章

最新更新