如何在Strongloop Loopback中更改http状态代码

eng*_*ran 5 rest http http-status-codes strongloop loopbackjs

我正在尝试修改create的http状态代码.

POST /api/users
{
    "lastname": "wqe",
    "firstname": "qwe",
}
Run Code Online (Sandbox Code Playgroud)

返回200而不是201

我可以为错误做些类似的事情:

var err = new Error();
err.statusCode = 406;
return callback(err, info);
Run Code Online (Sandbox Code Playgroud)

但是我找不到如何更改create的状态代码.

我找到了创建方法:

MySQL.prototype.create = function (model, data, callback) {
  var fields = this.toFields(model, data);
  var sql = 'INSERT INTO ' + this.tableEscaped(model);
  if (fields) {
    sql += ' SET ' + fields;
  } else {
    sql += ' VALUES ()';
  }
  this.query(sql, function (err, info) {
    callback(err, info && info.insertId);
  });
};
Run Code Online (Sandbox Code Playgroud)

Jak*_*ake 9

在您的通话中,remoteMethod您可以直接向响应添加功能.这是通过以下rest.after选项完成的:

function responseStatus(status) {
  return function(context, callback) {
    var result = context.result;
    if(testResult(result)) { // testResult is some method for checking that you have the correct return data
      context.res.statusCode = status;
    }
    return callback();
  }
}

MyModel.remoteMethod('create', {
  description: 'Create a new object and persist it into the data source',
  accepts: {arg: 'data', type: 'object', description: 'Model instance data', http: {source: 'body'}},
  returns: {arg: 'data', type: mname, root: true},
  http: {verb: 'post', path: '/'},
  rest: {after: responseStatus(201) }
});
Run Code Online (Sandbox Code Playgroud)

注意:如果context.result值为false ,似乎strongloop将强制204"无内容" .为了解决这个问题,我只需{}使用我想要的状态代码传回一个空对象.