【问题标题】:Express : using await before bcrypt.compare gives errorExpress:在 bcrypt.compare 之前使用 await 会出错
【发布时间】:2020-02-27 05:32:04
【问题描述】:

我正在尝试使用 bcrypt 将用户的密码与存储的密码进行比较。 但是 Express 给出的错误是我在 bcrypt.compare 之前使用 await

代码如下:

app.post ('/users/login', (req, res) => {
    const user = users.find(user=> user.name === req.body.user)
    if (user == null) {
        return res.status(400).send('Can Not find user');
    } else {
        try{
            if ( await bcrypt.compare(req.body.password, user.password)) {
                res.send("Success");
            } else {
                res.send("Incorrect PAssword");
            }
        } catch {
            return res.status(500).send('Some Error has occurred');
        }
    }
});

我收到此错误:

C:\Data\Ashish\projects\jwtAuthentication\app.js:32
            if ( await bcrypt.compare(req.body.password, user.password)) {
                       ^^^^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...

请帮忙找出错误..

问候, 灰烬

【问题讨论】:

    标签: node.js express bcrypt


    【解决方案1】:

    你忘记给回调函数添加异步了。

    app.post ('/users/login', (req, res) => {

    应该是:

    app.post ('/users/login', async (req, res) => {

    Await 仅适用于异步函数。

    它与 chrome 控制台不同。在控制台中可以直接使用 await 关键字,但对于 node.js,您需要指定要使用 await 的父函数的异步性质。

    更多参考可以参考this link

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 2021-05-28
      • 1970-01-01
      • 2021-10-07
      • 2017-11-25
      • 2021-10-09
      • 2021-11-01
      相关资源
      最近更新 更多