apostrophe - Apostrophe CMS:我们是否有可以从 API 设置 global.data 的中间件/挂钩?
问题描述
我的要求是我有一个提供用户数据的 API。在 Apostrophe CMS 中,我需要从所有布局(页眉、主要、页脚)访问用户数据。
我可以看到模板中随处可用的 gobal.data。同样,我需要一个钩子来调用 API 并将响应数据存储在撇号的 global.data 中。
如果您需要更多信息,请告诉我。
解决方案
您可以在每个页面渲染上点击该 API:
// index.js of some apostrophe module
// You should `npm install request-promise` first
const request = require('request-promise');
module.exports = {
construct: function(self, options) {
self.on('apostrophe-pages:beforeSend', async function(req) {
const apiInfo = await request('http://some-api.com/something');
req.data.apiInfo = apiInfo;
// now in your templates you can access `data.apiInfo`
});
}
}
但这会在每个请求上命中该 API,这当然会使您的网站变慢。因此,我建议您将信息缓存一段时间。
推荐阅读
- apache - PingFederate 和速度变量 $client_id
- java - 可选变量 - 变量可能未初始化
- javascript - Javascript条件计算系统
- python - 如何使用 Visual Studio 2017 连接到 Jupyter 笔记本
- eclipse - 即使我添加了有关它的所有必需文件,也显示无法解析平台名称的错误
- java - 多光标在某些计算机上不起作用(Netbeans)
- android - 片段中没有设置或显示任何内容
- python - 不明白为什么在 VS Code 中调试脚本会导致 AttributeError
- asp.net-core - OData v4 按多个基数属性排序
- mysql - 将一列与不同表中的另一列进行比较并将值输入另一列触发 MySQL