身份验证,使用快速JS

时间:2018-01-26 02:39:22

标签: javascript mysql angular typescript express

我需要帮助比较数据并将truefalse从静音端返回到服务器端,以检查电子邮件是否有效。在客户端,客户端将输入电子邮件并单击按钮进行验证,然后服务器将检查数据库是否存在电子邮件。如果电子邮件存在,则用户有效,如果电子邮件不存在,则客户端无效,无法继续下一页。我对express和一些mysql查询并不熟悉。我在postman应用程序中测试了我的代码,每次都返回valid。以下是来自mySql的一些示例电子邮件。

enter image description here

我在我的javascript express代码中使用app.post命令,但看起来我做错了,我错误地写了if语句。在postman应用程序中,当我检查它时,它总是返回valid并且在客户端我无法通过任何电子邮件进行身份验证。我不确定应该放什么条件,因为我并不熟悉快递。



app.post('/verifyEmail', (req, res) => {
  var email = req.body.email;
  let sql = 'SELECT * FROM email WHERE email = ?'; //incorrect condition checking
  let query = db.query(sql, (err, result) => {
    if (email == null || !email) { //incorrect condition checking
      throw err;
      res.send('invalid');
    }
    console.log('valid');
    res.send('valid');
  })
})




在客户端,我使用Angular和打字稿。



//service.ts
email: string[];
getEmailAPI(): Observable < any > {
  return this.http.get("http://localhost:8000/verifyEmail")
    .map((res: Response) => res.json())
    .catch((error: any) => Observable.throw(error.json().error || 'Server error'))
}

//component.ts
Email = [];
isVerified: boolean;
getEmailAPI() {
  this.QuestionService.getEmailAPI().subscribe(
    data => console.log('All email', this.Email = data),
    error => console.log('server returns error')
  );
}

verifyEmail(formValue) {
  this.AppService.getEmailAPI().subscribe(
    data => {
      if (data) {
        // do whatever needed is with returned data
        this.isVerified = true;
      } else {
        this.isVerified = false;
      }
    },
    error => console.log('server returns error')
  );
}
&#13;
<!--component.html-->
<form #emailVerification='ngForm' ngNativeValidate>
  <label>Please Enter Your Email Below</label>
  <input name="email" type="text" required/>
  <button type="submit" (click)="verifyEmail(emailVerification.value)">VERIFY</button>
</form>
&#13;
&#13;
&#13;

有人可以帮帮我吗?如果需要更多代码段,请告诉我。

1 个答案:

答案 0 :(得分:1)

您将始终有效,因为您正在检查电子邮件变量是否为空并且您的最终结果应该返回json.Since在您的客户端中您将获得json。将代码更改为以下

 app.post('/verifyEmail', (req, res) => {
  var email = req.body.email;
  let sql = 'SELECT count(*) as count FROM email WHERE email = ?';
  let query = db.query(sql, [email],(err, result) => {
    if (result[0].count == 1) {
      res.json({
        "data": "valid"
      })
    } else {

      res.json({
        "data": "invalid"
      })

    }
  });
});