javascript - 表达异步发布请求

标签 javascript node.js express asynchronous

我的代码

我在后端的代码将获取发布数据并调用异步函数

app.post('/login', async (req, res) => {
   var mail = decodeURIComponent(req.body.mail), password;
   await bcrypt.hash(decodeURIComponent(req.body.password), saltRounds, function(err, hash) {
       ...
   });
});

问题

如果我想启动应用程序,我会收到此警告:

[DEP0013] DeprecationWarning: Calling an asynchronous function without callback is depre

有没有更好的解决方案?

编辑

如果我只是这样做,我会得到同样的警告,但我不确定如何在这里进行回调。

app.post('/login', async (req, res) => { res.json({ success: true }); });

最佳答案

bcrypt(this one,对吧?)不是一个 promisified 库。

你不能等待它的功能。

app.post('/login', (req, res) => {
  bcrypt.hash(req.body.password, saltRounds, (err, result) => {
    if (err) {
      // error
      return;
    }
    // success
  });
});

但是你可以promisify如果你愿意的话。

const util = require('util');
const bcrypt = require('bcrypt');
const hashAsync = util.promisify(bcrypt.hash);

app.post('/login', (req, res) => {
  hashAsync(req.body.password, saltRounds).then(result => {
    // success
  }).catch(err => {
    // error
  });
});

当然上面也可以写成async/await。不过,不要忘记 try/catch

此外,我相信您不必进行任何 URL 解码。 req.body 中的所有值都已解码。自己调用 decodeURIComponent() 意味着您最终将解码这些值两次。一旦值实际上在某处包含类似%xx的内容,这将导致错误——尤其是在密码中,这迟早会发生。

关于javascript - 表达异步发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404786/

相关文章:

javascript - 正则表达式排除 URL

javascript - 在 ExtJS 中重写 getState

javascript - 重新加载在 ionic 应用程序中不起作用

javascript - 类型错误 : Cannot read property 'firstChild' of undefined While rendering the react page server side

reactjs - react 路由器4和表达: cannot GET

node.js - expressjs、nginx 代理、csurf 和安全 cookie 不起作用

javascript - IE 6 中的单击问题

node.js - 构建时,/dist 中缺少/src 手动创建的子文件夹

angularjs - 错误 : CSRF token missing, hackathon-starter 加 AngularJS

node.js - 页面未从 Express POST 路由呈现