首页 > 解决方案 > 访问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()???

标签: javascriptnode.js

解决方案


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 缓存,但你会找到必要的逻辑来完成你想要的。


推荐阅读