在 Loopback.js 中,如果它有一个 return 参数,如何响应一个空主体的远程方法?

In Loopback.js, how to respond to a remote method with an empty body if it has a return argument?

如果我有这样的远程方法:

Command.remoteMethod('invoke', {
  http: {verb: 'post', status: 200, source: 'body'},
  returns: {arg: "text", type: "string"}
});

有时我们需要用 text 参数来响应,有时我们需要用一个完全空的正文来响应。在远程方法代码中,我有这样的东西:

Command.invoke = callback => {
  // ...

  if (error) {
    callback(null, 'There was an error');
  } else {
    callback(null);
  }
}

问题是,在 else 分支中,正文永远不会为空。我也尝试过:callback(null, null)callback(null, '')

有办法实现吗?或者我是否需要实现一个远程挂钩来手动修改响应以获得我想要的?

当您在 model.js 中定义一个 returns 块时,这意味着您的远程方法有一个响应主体。

根据您的情况,您可以删除远程挂钩中的结果。

Command.afterRemote("invoke", function(ctx, instance, next){
        //check if you want return text or nothing
        //if nothing so set result to null, otherwise just call next()
        ctx.result = null;
        next();
    });

最好的方法是使用后远程功能

如果没有内容可以添加

ctx.res.statusCode = 204
ctx.res.end(null);