首页 > 解决方案 > Apostrophe CMS:我们是否有可以从 API 设置 global.data 的中间件/挂钩?

问题描述

我的要求是我有一个提供用户数据的 API。在 Apostrophe CMS 中,我需要从所有布局(页眉、主要、页脚)访问用户数据。

我可以看到模板中随处可用的 gobal.data。同样,我需要一个钩子来调用 API 并将响应数据存储在撇号的 global.data 中。

如果您需要更多信息,请告诉我。

标签: apostropheapostrophe-cms

解决方案


您可以在每个页面渲染上点击该 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,这当然会使您的网站变慢。因此,我建议您将信息缓存一段时间。


推荐阅读