如何将loopback API响应更改为特定格式

byt*_*0de 1 api node.js express loopbackjs

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

例如:如果成功

{
    status:1,
    data:{},
    message:"Success"
}
Run Code Online (Sandbox Code Playgroud)

如果错误

{
    status:0,
    data:{},
    message:"Something went wrong"
}
Run Code Online (Sandbox Code Playgroud)

Ano*_*cem 5

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

/ 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();
});
Run Code Online (Sandbox Code Playgroud)

};

查看这些链接以获取更多信息:

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

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

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