Javascript 在节点js中使用电子邮件、电话或用户名登录
如何在node js和mongodb中使用密码登录电子邮件、电话或用户名? 用户可以使用电子邮件和密码、用户名和密码、电话和密码登录。 这类似于Instagram登录模块。 这是我的剧本:Javascript 在节点js中使用电子邮件、电话或用户名登录,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,如何在node js和mongodb中使用密码登录电子邮件、电话或用户名? 用户可以使用电子邮件和密码、用户名和密码、电话和密码登录。 这类似于Instagram登录模块。 这是我的剧本: const login=catchAsync(async(req,res)=>{ const{email,password}=req.body; const user=wait user.findOne({email}); 如果(!user | |!(等待user.isPasswordMatch(密码))){
const login=catchAsync(async(req,res)=>{
const{email,password}=req.body;
const user=wait user.findOne({email});
如果(!user | |!(等待user.isPasswordMatch(密码))){
抛出新的ApiError(httpStatus.UNAUTHORIZED,“错误的电子邮件或密码”);
}
const tokens=wait tokenService.generateAuthTokens(user.id);
const response={user:user.transform(),tokens};
res.send(响应);
});
首先,您需要检查电子邮件和密码是否存在,然后您需要检查电子邮件和密码组合是否正确。
在您的情况下,您还可以添加一个字段,例如带有电子邮件的手机
const login = catchAsync(async (Request, Response, next) => {
const { email, password } = Request.body;
//check if email and password exists
if (!email || !password) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'Please provide email and password');
}
//check if user exist and password correct
const user = await User.findOne({ email }).select('+password');
if (!user || !(await user.isPasswordMatch(password, user.password))) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'Incorrect email or password');
}
//if everything ok, send token to the client
const tokens = await tokenService.generateAuthTokens(user.id);
const response = { user: user.transform(), tokens };
res.send(response);
});
附言:直接抛出错误是不好的做法。使用不同的方法。您可以尝试的是,不要限制您的代码接受电子邮件,只需将其设置为一般性的,并根据这样的输入查找用户
const login=catchAsync(async(req,res)=>{
常数{
用户电子邮件电话,
密码
}=请求主体;
//假设在数据库中有电子邮件、电话和用户名字段
const user=wait user.findOne({
$or:[{
“电子邮件”:用户电子邮件电话
}, {
“电话”:用户电子邮件电话
}, {
“用户名”:userEmailPhone
}]
});
如果(!user | |!(等待user.isPasswordMatch(密码))){
抛出新的ApiError(httpStatus.UNAUTHORIZED,“错误的电子邮件或密码”);
}
const tokens=wait tokenService.generateAuthTokens(user.id);
常数响应={
用户:user.transform(),
代币
};
res.send(响应);
});代码>