修改 feathers 中的响应状态码 hook.result
Modifying response status code in feathers hook.result
我最近一直在玩 feathers.js,我喜欢它。我有以下问题但是...
在为 update (http put)
服务器方法放置的前挂钩中,我根据某些条件决定是 create
还是 update
。如果我选择 create
,我会使用 hook.result
跳过服务方法
let createLocation = (hook) => {
return hook.app.service('locations').create({
"user": hook.data.user,
"location": [{
"latitude": hook.data.location[0].latitude,
"longitude": hook.data.location[0].longitude
}]
}).then(location => {
hook.result = location;
//************ change the response status code here?? **************\
});
};
但我无法将响应状态代码更改为坚持201 created
。帮助将不胜感激。 (也请指出源代码,如果可能的话,我搜索了但没有成功)。
服务和挂钩是独立于传输的,这就是为什么它们可以通过 websockets 和 HTTP 使用。任何 HTTP 特定的逻辑都应该存在于它自己的中间件中。有两种选择。要设置所有服务的状态代码,您可以实施 a custom formatter, for only a specific service you can register service specific middleware.
如果没有办法从数据中扣除状态码,你可以在数据上define a hidden property(不可写,转换为JSON时不会显示)对象:
let createLocation = (hook) => {
return hook.app.service('locations').create({
"user": hook.data.user,
"location": [{
"latitude": hook.data.location[0].latitude,
"longitude": hook.data.location[0].longitude
}]
}).then(location => {
Object.defineProperty(location, '__status', {
value: 201
});
hook.result = location;
});
};
并在自定义格式化程序中使用它:
const app = feathers();
function restFormatter(req, res) {
res.format({
'application/json': function() {
const data = res.data;
res.status(data.__status || 200);
res.json(data);
}
});
}
app.configure(rest(restFormatter));
还有其他选项,例如 passing the response to params 或者返回具有附加元信息的包装器对象 ({ status, data }
)。
我最近一直在玩 feathers.js,我喜欢它。我有以下问题但是...
在为 update (http put)
服务器方法放置的前挂钩中,我根据某些条件决定是 create
还是 update
。如果我选择 create
,我会使用 hook.result
let createLocation = (hook) => {
return hook.app.service('locations').create({
"user": hook.data.user,
"location": [{
"latitude": hook.data.location[0].latitude,
"longitude": hook.data.location[0].longitude
}]
}).then(location => {
hook.result = location;
//************ change the response status code here?? **************\
});
};
但我无法将响应状态代码更改为坚持201 created
。帮助将不胜感激。 (也请指出源代码,如果可能的话,我搜索了但没有成功)。
服务和挂钩是独立于传输的,这就是为什么它们可以通过 websockets 和 HTTP 使用。任何 HTTP 特定的逻辑都应该存在于它自己的中间件中。有两种选择。要设置所有服务的状态代码,您可以实施 a custom formatter, for only a specific service you can register service specific middleware.
如果没有办法从数据中扣除状态码,你可以在数据上define a hidden property(不可写,转换为JSON时不会显示)对象:
let createLocation = (hook) => {
return hook.app.service('locations').create({
"user": hook.data.user,
"location": [{
"latitude": hook.data.location[0].latitude,
"longitude": hook.data.location[0].longitude
}]
}).then(location => {
Object.defineProperty(location, '__status', {
value: 201
});
hook.result = location;
});
};
并在自定义格式化程序中使用它:
const app = feathers();
function restFormatter(req, res) {
res.format({
'application/json': function() {
const data = res.data;
res.status(data.__status || 200);
res.json(data);
}
});
}
app.configure(rest(restFormatter));
还有其他选项,例如 passing the response to params 或者返回具有附加元信息的包装器对象 ({ status, data }
)。