【问题标题】:Angular and express server communication issuesAngular 和 Express 服务器通信问题
【发布时间】:2021-11-09 13:56:09
【问题描述】:

我必须创建一个简单的 Angular/Express/mLab 组合,让您可以创建用户并验证他们。 我在我的 Angular 项目中创建了一个服务

createTest(email: string, name: string, password: string) {
    this.http.post(this.createUserURL, {
      "name": name,
      "email": email,
      "password": password
    }).subscribe();
  }

和快递方面:

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 进行操作。 我该怎么做?

【问题讨论】:

    标签: angular express mlab


    【解决方案1】:

    您需要将一个接收和处理 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 */ });
          }
    

    但我想知道为什么密码匹配时返回错误?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多