简体   繁体   中英

How to change http status codes in Strongloop Loopback

I am trying to modify the http status code of create.

POST /api/users
{
    "lastname": "wqe",
    "firstname": "qwe",
}

Returns 200 instead of 201

I can do something like that for errors:

var err = new Error();
err.statusCode = 406;
return callback(err, info);

But I can't find how to change status code for create.

I found the create method:

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);
  });
};

In your call to remoteMethod you can add a function to the response directly. This is accomplished with the rest.after option:

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) }
});

Note: It appears that strongloop will force a 204 "No Content" if the context.result value is falsey. To get around this I simply pass back an empty object {} with my desired status code.

You can specify a default success response code for a remote method in the http parameter.

MyModel.remoteMethod(
  'create',
  {
    http: {path: '/', verb: 'post', status: 201},
    ...
  }
);

For loopback verion 2 and 3+: you can also use afterRemote hook to modify the response:

module.exports = function(MyModel) {  
  MyModel.afterRemote('create', function(
    context,
    remoteMethodOutput,
    next
  ) {
    context.res.statusCode = 201;
    next();
  });
};

This way, you don't have to modify or touch original method or its signature. You can also customize the output along with the status code from this hook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM