【问题标题】:Can I get to response headers in Loopback afterRemote hook?我可以在远程挂钩后访问 Loopback 中的响应标头吗?
【发布时间】:2015-03-13 23:38:34
【问题描述】:

我有一个 Loopback 模型,我在该模型上使用 afterRemote 钩子将请求记录到敬业度。 http://docs.strongloop.com/display/public/LB/Remote+hooks#Remotehooks-ctx.result

我也在使用响应时间包将响应时间标头添加到响应中。 https://github.com/expressjs/response-time

这工作正常,预计我无法弄清楚如何获取响应中的 X-Response-Time 标头以便将其记录到keen.io。

我可以通过以下任何方式访问响应标头吗?

module.exports = function(Studio) {
    var isStatic = true;
    var isNotStatic = false;
    Studio.disableRemoteMethod('deleteById', isStatic); // DELETE /Studios/{id}
    Studio.disableRemoteMethod('create', isStatic); // POST /Studios
    Studio.disableRemoteMethod('upsert', isStatic); // PUT /Studios
    Studio.disableRemoteMethod('updateAll', isStatic); // POST /Studios/update
    Studio.disableRemoteMethod('updateAttributes', isNotStatic); // PUT /Studios/{id}
    Studio.disableRemoteMethod('__create__ListenNps', isNotStatic);
    Studio.disableRemoteMethod('__delete__ListenNps', isNotStatic);
    Studio.disableRemoteMethod('__destroyById__ListenNps', isNotStatic);
    Studio.disableRemoteMethod('__updateById__ListenNps', isNotStatic);

    Studio.afterRemote('*', function(ctx, affectedModelInstance, next) {
        var Keen = require('keen-js');

        var client = new Keen({
            projectId: "myid",
            writeKey: "mykey"
        });

        var queryEvent = {
            ip: ctx.req.ip,
            baseUrl: ctx.req.baseUrl,
            url: ctx.req.url,
            route: ctx.req.route,
            query: ctx.req.query,
            method: ctx.methodString,
            // response: ctx.result.???, What can I do here to get to the response headers? Specifically X-Response-Time
            keen: {
                timestamp: new Date().toISOString()
            }
        };

        client.addEvent("queries", queryEvent, function(err, res) {
            if (err) {
                console.log(err)
            } else {
                console.log(res)
            }
        });
        next();
    });
};

【问题讨论】:

    标签: express loopbackjs strongloop keen-io


    【解决方案1】:

    尝试使用ctx.res.getHeader('X-Response-Time')method

    收听res.on('finish')event

    【讨论】:

    • 感谢您的回复,但我似乎无法在这种情况下使用它。我不确定是否可以在 afterRemote 方法中访问标题。
    • 是的,我错过了标题可能尚未定义。所以我完成了答案!
    猜你喜欢
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 2023-01-01
    • 2021-05-31
    • 2015-02-13
    • 1970-01-01
    相关资源
    最近更新 更多