Rest 如何更改Strongloop环回中的http状态代码
我正在尝试修改create的http状态代码Rest 如何更改Strongloop环回中的http状态代码,rest,http,http-status-codes,loopbackjs,strongloop,Rest,Http,Http Status Codes,Loopbackjs,Strongloop,我正在尝试修改create的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 = fun
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);
});
};
在对
remoteMethod
的调用中,可以直接向响应中添加函数。这是通过rest完成的。在选项之后:
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) }
});
注意:如果context.result
值为false,则strongloop将强制204“无内容”。为了解决这个问题,我只需传回一个空对象{}
和我想要的状态代码。您可以在http参数中为远程方法指定默认的成功响应代码
MyModel.remoteMethod(
'create',
{
http: {path: '/', verb: 'post', status: 201},
...
}
);
对于环回verion 2和3+:您还可以使用afterRemote
hook修改响应:
module.exports = function(MyModel) {
MyModel.afterRemote('create', function(
context,
remoteMethodOutput,
next
) {
context.res.statusCode = 201;
next();
});
};
这样,您就不必修改或触摸原始方法或其签名。您还可以自定义输出以及来自此挂钩的状态代码。我也一直在尝试解决这个问题。更全面的文档最好是:(