从快递中间件访问数据
我在node.js中构build一个应用程序。
我写了一个中间件函数钩子,当有人在我的应用程序上发出GET请求时就执行它,就像他们进入主页,configuration文件页面等一样。钩子从另一个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端的内容。 有没有人有任何想法如何做到这一点?
您可以在req
和res
对象中设置自定义variables。 就像下面的代码将被存储在req.my_data
上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(); }); } } };
而在您的路线中,通过将数据传递给模板引擎,您可以在客户端访问该数据。 根据你的模板引擎( ejs
, jade
等),语法不尽相同。
router.get('/', function(req, res, next) { res.render('../views/home', {data: req.my_data}); });