如何在Strongloop Loopback中更改http状态代码 [英] How to change http status codes in Strongloop Loopback
问题描述
我正在尝试修改create的http状态代码。
I am trying to modify the http status code of create.
POST /api/users
{
"lastname": "wqe",
"firstname": "qwe",
}
返回200而不是201
Returns 200 instead of 201
我可以为错误做点什么:
I can do something like that for errors:
var err = new Error();
err.statusCode = 406;
return callback(err, info);
但是我找不到如何更改create的状态代码。
But I can't find how to change status code for 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.after
选项完成的:
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) }
});
注意:如果 context.result
值为falsey。为了解决这个问题,我只需使用我想要的状态代码传回空对象 {}
。
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.
这篇关于如何在Strongloop Loopback中更改http状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!