2014-11-14 79 views
5

我试图修改创建的http状态代码。如何更改Strongloop Loopback中的http状态代码

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

返回200,而不是201

我可以为错误,做这样的事情:

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

但我无法找到如何更改状态代码创建。

我发现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); 
    }); 
}; 
+0

我一直在试图弄清楚这一点。更全面的文档将是不错的:( – Jake 2014-11-15 03:17:37

回答

8

在您的来电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) } 
}); 

注:看来,strongloop将迫使204“无内容”如果context.result值falsey。为了解决这个问题,我只需传回一个空的对象{}与我想要的状态代码。

+0

谢谢!它的工作原理!但现在我使用http://sailsjs.org/#/,更灵活。 – enguerran 2014-11-18 10:07:48

1

您可以在http参数中指定远程方法的默认成功响应代码。

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