从 express 中间件访问数据

Tru*_*ran 1 javascript middleware node.js express

我正在 node.js 中构建一个应用程序。

我编写了一个中间件函数钩子,每当有人在我的应用程序上发出 GET 请求时都会执行该钩子,比如他们进入主页、个人资料页面等。该钩子从另一个 API 发出 HTTP 请求以收集数据。

我的问题是如何在客户端访问该数据?这是我的中间件钩子:

var request = require('request');

module.exports = {
    authentication: function (req, res, next) {
       if (req.method === 'GET') { 
        console.log('This is a GET request');
         request("http://localhost:3000/api/employee", function(err, res, body) {
            console.log(res.body);
         });
       }
       next();
    }
};
Run Code Online (Sandbox Code Playgroud)

它用于我的所有路线:

app.use(middleware.authentication)

示例路线:

router.get('/', function(req, res, next) {
    res.render('../views/home');
});
Run Code Online (Sandbox Code Playgroud)

注意我使用了console.log(res.body),但我想在客户端打印它的内容。有谁知道如何做到这一点?

Aᴍɪ*_*ᴍɪʀ 5

您可以在reqres对象中设置自定义变量。就像下面的代码将被存储在req.my_data. 稍后在您的路线中,您可以req再次检索它。

并且,您需要next()在获得数据后调用,否则代码会在您从request.

var request = require('request');

module.exports = {
    authentication: function (req, res, next) {
       if (req.method === 'GET') { 
        console.log('This is a GET request');
         request("http://localhost:3000/api/employee", function(err, request_res, body) {
            req.my_data = request_res.body;
            next();
         });
       }

    }
};
Run Code Online (Sandbox Code Playgroud)

在您的路线中,通过将数据传递给模板引擎,您可以在客户端访问该数据。根据您的模板引擎(ejsjade等...),语法会有所不同。

router.get('/', function(req, res, next) {
    res.render('../views/home', {data: req.my_data});
});
Run Code Online (Sandbox Code Playgroud)