簡體   English   中英

從快速中間件訪問數據

[英]Access data from express middleware

我在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();
    }
};

我的所有路線都使用了它:

app.use(middleware.authentication)

樣本路線:

router.get('/', function(req, res, next) {
    res.render('../views/home');
});

注意,我使用console.log(res.body) ,但是我想在CLIENT端打印該內容。 有誰知道如何做到這一點?

您可以在reqres對象中設置自定義變量。 就像下面的代碼將被存儲在req.my_datareq.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();
         });
       }

    }
};

並且在您的路由中,通過將數據傳遞到模板引擎,您可以在客戶端進行訪問。 根據您的模板引擎( ejsjade等...),語法會有所不同。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM