繁体   English   中英

身份验证,使用Express JS比较从客户端输入的数据与服务器端的mySql

[英]Authentication, Compare data input from client side with mySql in server side using express JS

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

在此处输入图片说明

我在我的javascript Express代码中使用了app.post命令,但看起来我做错了,并且我写错了if语句。 在邮递员应用程序中,当我对其进行检查时,它将始终返回valid并且在客户端,我无法使用任何电子邮件进行身份验证。 我不确定应该设置什么条件,因为我不太了解Express。

 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与Typescript一起使用。

 //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') ); } 
 <!--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> 

有人可以帮我吗? 请让我知道是否需要更多片段。

由于您正在检查email变量是否为null且最终结果应返回json,因此您将始终有效。由于在客户端中,您将获取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"
      })

    }
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM