【问题标题】:Authentication, Compare data input from client side with mySql in server side using express JS身份验证,使用 express JS 将来自客户端的数据输入与服务器端的 mySql 进行比较
【发布时间】:2018-07-05 10:07:14
【问题描述】:

我需要帮助比较数据并从客户端返回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>

有人可以帮帮我吗?如果需要更多 sn-ps,请告诉我。

【问题讨论】:

    标签: javascript mysql angular typescript express


    【解决方案1】:

    您将始终有效,因为您正在检查电子邮件变量是否为空,并且您的最终结果应该返回 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"
          })
    
        }
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-21
      • 2017-10-07
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      相关资源
      最近更新 更多