简体   繁体   中英

Access data from express middleware

I am building an application in node.js.

I wrote a middleware function hook that executes whenever someone makes a GET request on my app, like if they go to the home page, profile page, etc. The hook makes a HTTP request from another API to collect data.

My question is how can I access that data on the client side? Here is my middleware hook:

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

It is used in all my routes:

app.use(middleware.authentication)

Sample route:

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

Notice I used console.log(res.body) , but I want to print the contents of that on the CLIENT side. Does anyone have any idea how to do this?

You can set custom variables in req and res objects. Just like the code below which it is going to be stored on req.my_data . Later in your route, you can retrieve it from req again.

And, you need to call next() after you got the data, otherwise the code continues on before you get the data from 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();
         });
       }

    }
};

And in your route, by passing the data to the template engine, you can have access that on the client side. Depending on your template engine ( ejs , jade etc ...), the syntax vary.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM