javascript - 访问nodejs中的resonse结果
问题描述
我想访问 nodejs 中的响应数据。
我在 redis 中有用于缓存的中间件。如果redis中存在数据,则返回数据,如果不存在,则转到数据库并返回数据。
我的问题是数据库中不存在数据时。
我想当redis中不存在数据时,从数据库中获取数据,当向客户端发送数据时,将数据设置为redis。
我为 redis 缓存创建了一个中间件:
module.exports = new (class RedisMiddllware {
Cache(req, res, next) {
redis.Get(req.path).then((response)=>{
if (response !== null) {
new OkObjectResult(response).Send(res);
} else {
next();
}
}).catch((error)=>{
throw new Error(error)
})
}
})();
我想 next();
在 redis 中设置数据,但是当我使用它时,res
它不显示返回数据。
我通过这种方式返回数据:
res.status(400).json({
message: success,
data:{
"isDelete": false,
"_id": "5f4134984cb63a0ca49a574d",
"name": "Farsi",
"flag": "IR",
"unit": "Rial",
"createDate": "Sat Aug 22 2020 19:37:04 GMT+0430 (Iran Daylight Time)",
"createBy": "kianoush",
"__v": 0,
"updateBy": "kianoush",
"updateDate": "Sat Aug 22 2020 20:38:23 GMT+0430 (Iran Daylight Time)",
"deleteDate": "Sun Aug 23 2020 13:31:07 GMT+0430 (Iran Daylight Time)",
"deleteby": "kianoush",
"id": "5f4134984cb63a0ca49a574d"
},
statusCode:200,
success: true,
});
从resonse 之后,我如何访问 middllware 中的结果数据next()
???
解决方案
NodeJS 中间件按顺序独立执行,并在执行“response.send()”或等效项后立即停止执行。简而言之,如果您在端点上定义了 3 个中间件函数(md1、md2、md3)。然后 Node 将首先调用 md1,如果 md1 执行“response.send()”,则根本不调用 md2 和 md3。如果 md1 执行“next()”,则调用 md2,但它不知道 md1。此外,它不像函数调用树,在 md2 执行后控制返回到 md1。
有了所有的理论,您需要在从数据库中获取结果后将结果放入 Redis 缓存中,在您正在调用数据库并可能执行“response.json()”的同一函数中也是。
请查看 REPL:https ://unselfishvoluminouscad.deepakchampatir.repl.co
它不使用 Redis 缓存,但你会找到必要的逻辑来完成你想要的。
推荐阅读
- node.js - 如果服务器成功处理了请求但没有返回任何内容,如何在邮递员中打印得到响应?
- rpm - rpm.spec 中设置 systemd 预设的正确命令是什么
- tensorflow - 使用 ImageDataGenerator 进行 Keras 数据增强(您的输入没有数据)
- android - armeabi-v7a 上的 Flutter 应用程序性能
- java - Intellij 升级后 Gradle 不再构建:java.lang.NoClassDefFoundError: org/jetbrains/plugins/gradle/tooling/ModelBuilderService$Ex
- python - 连续计数 1
- azure - 安装的 Grafana 插件是否会进行外部调用?
- html - Pydeck 工具提示格式数字
- c++ - '当一个大块被“锁定”在较小的块之间'时,mmap 不起作用是什么意思?
- javascript - 使用异步回调处理事件