【问题标题】:Get User-Agent and Timezone in mixins在 mixins 中获取 User-Agent 和 Timezone
【发布时间】:2019-05-31 19:51:17
【问题描述】:

我正在为“创建”钩子上的模型创建一个 mixin。我想访问用户代理和用户时区信息。

我也尝试过使用 LoopBackContext。但这并没有多大帮助,因为我找不到包含这些信息的对象。

var loopBackContext = require('loopback-context');

module.exports = function Request(Model, options) {
  Model.observe('access', function event(ctx, next) {
   var httpContext = loopBackContext.getCurrentContext();
    //access user-agent and timezone
    next();
  });
};

【问题讨论】:

    标签: node.js loopback


    【解决方案1】:

    请注意loopback-context 不能非常可靠地工作,我们建议通过options 对象传递上下文,如https://loopback.io/doc/en/lb3/Using-current-context.html 中所述。

    传递给像access 这样的操作钩子的ctx 参数是另一种类型的上下文对象,请参阅Operation hooks 上的文档。

    要访问其他请求标头,您还应该覆盖 Model 的 createOptionsFromRemotingContext 方法,请参阅 https://loopback.io/doc/en/lb3/Using-current-context.html#override-createoptionsfromremotingcontext-in-your-model

    module.exports = function Request(Model, options) {
      Model.createOptionsFromRemotingContext = function(ctx) {
        const base = this.base.createOptionsFromRemotingContext(ctx);
        return {
          ...base,
          userAgent: req.headers['user-agent'],
          // etc.
        };
      });
    
      Model.observe('access', function event(ctx, next) {
        const options = ctx.options || {};
        // options contains data created by Model.createOptionsFromRemotingContext
        // but only when invoked via REST API.
        // when called from JavaScript (e.g. from unit-tests), options are exactly
        // as provided by the caller (often undefined).
        const userAgent = ctx.options && ctx.options.userAgent;
        // access user-agent and timezone
        next();
      });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      相关资源
      最近更新 更多