Express:在bcrypt.compare给出错误之前使用await

Ash*_*ish 0 bcrypt node.js express

我正在尝试使用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');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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...
Run Code Online (Sandbox Code Playgroud)

请帮助找到错误。

问候,Ashish

Abh*_*rma 5

您忘记将异步添加到回调函数。

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

应该:

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

Await仅适用于异步功能。

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

有关更多参考,请参考此链接