【问题标题】:How to change loopback API response to a particular format如何将环回 API 响应更改为特定格式
【发布时间】:2018-08-30 04:12:12
【问题描述】:

我是环回新手,我想将来自环回远程方法 API 的每个响应更改为特定格式

例如:如果成功

{
    status:1,
    data:{},
    message:"Success"
}

如果出错

{
    status:0,
    data:{},
    message:"Something went wrong"
}

【问题讨论】:

    标签: node.js api express loopbackjs


    【解决方案1】:

    您应该创建一个引导脚本来更改所有远程方法响应:

    /server/boot/

    中创建 hook.js 或任何其他名称
    module.exports = function (app) {
    var remotes = app.remotes();
    // modify all returned values
    remotes.after('**', function (ctx, next) {
        if (ctx) {
            ctx.result = {
                status: 1,
                data: ctx.result,
                message: "Success"
            };
        } else {
            var err = new Error();
            next({
                status: 0,
                data: err,
                message: "Something went wrong"
            });
        }
        next();
    });
    

    };

    查看这些链接了解更多信息:

    格式化远程方法响应(最后一节)

    https://loopback.io/doc/en/lb3/Remote-methods.html

    挂钩

    https://loopback.io/doc/en/lb3/Strong-Remoting.html

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多