退出自定义 Sails 1 和 Actions 2

Leo*_*tas 3 node.js sails.js

如果我想使用 Actions 2 在sails 1 中返回带有状态代码和错误消息的一些错误的输出。怎么办?

前任:

...

  exits: {
    notFound: {
      description: 'not found',
      responseType: 'notFound'
    }

...
Run Code Online (Sandbox Code Playgroud)

退出会怎样?例如:状态代码 403 和消息“不允许”

Fel*_*gas 5

编辑:我尝试了幼稚的方法,它奏效了!您可以将非成功退出作为函数返回,并将 json 作为参数传递。示例代码:

return exits.notfound({
    error: true,
    message: 'The *thing* could not be found in the database.'
});
Run Code Online (Sandbox Code Playgroud)

原始答案:

您可以从操作 2 访问响应对象,并将错误代码和消息放在那里。

在您的出口中,只需设置您想要的状态代码,并在操作本身中根据特定出口修改您的资源,然后再抛出它。

...

exits: {
    notFound: {
      statusCode: 403,
      description: 'not found'
    }

...
Run Code Online (Sandbox Code Playgroud)

在你的行动中:

...

if(!userRecord) {
  this.res.message = 
    {
        exit: 'notFound', 
        message: 'The *thing* could not be found in the database.'
    };
  throw 'notFound';
}

...
Run Code Online (Sandbox Code Playgroud)

您可以设置自定义响应来做同样的事情。将 responseType 放入您的操作 2 退出中,如下所示:

...

exits: {
    notFound: {
      responseType: 'notfound',
      description: 'not found'
    }

...
Run Code Online (Sandbox Code Playgroud)

然后在 api/responses 中创建您的自定义响应并在那里设置状态代码和消息。

...

module.exports = function notfound() {
    let req = this.req;
    let res = this.res;

    sails.log.verbose('Ran custom response: res.notfound()');

    res.message = 
        {
            exit: 'notFound', 
            message: 'The *thing* could not be found in the database.'
        };
      return res.status(403);
    }

...
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚发现你必须在 fn 的输入和出口中发送参数,比如 fn: async function(inputs,exits) (2认同)