我的代码
我在后端的代码将获取发布数据并调用异步函数
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/