loopbackjs – 修改ctx.result不会更改POST响应

我正在修改我的模型上的ctx.result后保存操作钩子来简化POST方法的响应.响应应仅包含生成的id和仅响应属性,该属性不属于模型:

MyModel.observe('after save', function(ctx, next) {
    if (ctx.instance && ctx.isNewInstance) {
        ctx.result = {
            id : ctx.instance.id,
            responseOnlyProperty: MyModel.getResponseOnlyPropertyValue()
        };
        console.log('result:', ctx.result);
    }
    next();
});

正如预期的那样,ctx.result被写入控制台并设置了新值,但发送回客户端的响应主体仍然包含所有模型属性,并且不包含新添加的responseOnlyProperty.

修改响应体的正确方法是什么?

最佳答案 他们建议使用afterRemote钩子来调整响应:
how to modify the responses loopback sends.所以,只需将您实现的逻辑移动到该方法中即可.很有可能,ctx.result会在后期填充,这就是为什么你在模型钩子中放入ctx.result的内容会被覆盖.

点赞