要添加您自己的自定义响应方法,只需将一个文件添加到/api/responses
,并使用您想要创建的方法的名称命名。该文件应导出一个函数,该函数可以接受任何您想要的参数。
/**
* api/responses/myResponse.js
*
* This will be available in controllers as res.myResponse('foo');
*/
module.exports = function(message) {
var req = this.req;
var res = this.res;
var viewFilePath = 'mySpecialView';
var statusCode = 200;
var result = {
status: statusCode
};
// Optional message
if (message) {
result.message = message;
}
// If the user-agent wants a JSON response, send json
if (req.wantsJSON) {
return res.json(result, result.status);
}
// Set status code and view locals
res.status(result.status);
for (var key in result) {
res.locals[key] = result[key];
}
// And render view
res.render(viewFilePath, result, function(err) {
// If the view doesn't exist, or an error occured, send json
if (err) {
return res.json(result, result.status);
}
// Otherwise, serve the `views/mySpecialView.*` page
res.render(viewFilePath);
});
}