【发布时间】:2022-01-14 15:16:02
【问题描述】:
我想创建一个快速中间件来执行基本检查授权标头中的用户/密码对是否存在于 JSON 文件中(教育目的)。我将它添加到一个非常简单的单位转换器应用程序中。
问题是当用户名/密码正确时,我收到的是 403 而不是资源。
我发现当我执行请求时,中间件中的 Promise.then 在我的函数 findUserByCredentials 中实现 Promise 之前执行。请参阅下面第三个代码 sn-p 中的问题说明。
index.js
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const findUserByCredentials = require("./lib/find-user");
app.use(function (req, res, next) {
if (req.headers) {
let header = req.headers.authorization || '';
let [type, payload] = header.split(' ');
if (type === 'Basic') {
let credentials = Buffer.from(payload, 'base64').toString('ascii');
let [username, password] = credentials.split(':');
findUserByCredentials({username, password}).then(() => {
console.log("next")
next();
}).catch(() => {
console.log("403")
res.sendStatus(403);
});
}
} else {
next();
}
});
app.get('/inchtocm', (req, res) => {
const cm = parseFloat(req.query.inches) * 2.54;
res.send({"unit": "cm", "value": cm});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
module.exports = app;
./lib/find-user.js
const bcrypt = require('bcrypt');
const jsonfile = require('../users.json');
let findUserByCredentials = () => (object) => {
const username = object.username;
const password = object.password;
return new Promise((resolve, reject) => {
jsonfile.forEach(user => {
if (user.username === username) {
bcrypt.compare(password, user.password).then((buffer) => {
if (buffer) {
console.log("resolve")
resolve();
} else {
console.log("reject")
reject();
}
});
}
});
reject();
});
};
module.exports = findUserByCredentials();
发送请求后的服务器控制台
Example app listening at http://localhost:3000
403
resolve
如何强制 Express 在执行第二个操作之前等待第一个 Promise 完成?
【问题讨论】:
标签: javascript node.js express