我必须创建一个简单的Angular/Express/mLab组合,让你创建用户并验证他们。我在angular项目中创建了一个服务
createTest(email: string, name: string, password: string) {
this.http.post(this.createUserURL, {
"name": name,
"email": email,
"password": password
}).subscribe();
}
And express side:
app.post("/create_user",async (req:express.Request,res:express.Response)=>{
try{
if(await User.findOne({email:req.body.email})){
res.status(400).json({ message: "Email already taken!" });
}else{
req.body.password = await bcrypt.hash(req.body.password,10);
const myUser = new User(req.body)
await myUser.save()
}
}catch (err){
res.send(err);
}
})
效果很好;我可以创建一个用户。然后我想验证注册用户,为此我还创建了必要的函数:
角:
login(email: string, password: string) {
this.http.post(this.logInUserURL, {
"email": email,
"password": password
}).subscribe();
}
表达:
app.post('/login',async (req:express.Request,res:express.Response) => {
const body = req.body;
const user = await User.findOne({email: body.email});
if(user){
if(await bcrypt.compare(body.password,user.password)){
res.status(400).json({ error: "Valid Password" });
}else{
res.status(400).json({ error: "Invalid Password" });
}
}
})
之后,我希望能够在Angular端接收确认(例如接收像loginSucces:true这样的布尔值),以便我可以使用UI操作。我该怎么做呢?
您需要像这样传递一个接收和处理HTTP响应数据的函数给.subscribe()
:
login(email: string, password: string) {
this.http.post(this.logInUserURL, {
"email": email,
"password": password
}).subscribe((data: /* The type of your response */) => { /* YOUR CODE TO DO SOMETHING WITH THE DATA */ });
}
但是我想知道为什么当密码匹配时你会返回一个错误?