Express 中间件配置响应
Express middleware to configure response
我想创建一个中间件来自动格式化我的输出,returns它的格式看起来像
{
"successful": "true",
"message": "Successfully created",
"data": {
"name": "Joe",
"year": 1
}
}
目前我只是返回数据本身的 json(名称、年份等)
我要添加"successful"、"message"等
下面是我的一些代码片段:
routes/student.js
var student_controller = require('../controllers/studentController');
router.get('/list', student_controller.student_list);
controllers/student.js
var Student = require('../models/student');
exports.student_list = function(req, res, next) {
Student.find()
.exec(function(err, list_students) {
if (err) {return next(err);}
res.json(list_students);
});
};
app.js
var studentRouter = require('./routes/student');
app.use('/student', studentRouter);
我如何制作这个中间件,我应该在哪个文件中调用它?
可以通过覆盖 response.json
函数来拦截响应。通过这样做,并添加我们的custom function
,每次调用response.json()
,我们的拦截功能就会被触发。
middleware/response.filter.js:
// Response Interceptor Middleware
export default (request, response, next) => {
try {
const oldJSON = response.json;
response.json = (data) => {
// For Async call, handle the promise and then set the data to `oldJson`
if (data && data.then != undefined) {
// Resetting json to original to avoid cyclic call.
return data.then((responseData) => {
// Custom logic/code. -----> Write your logic to add success wrapper around the response
response.json = oldJSON;
return oldJSON.call(response, responseData);
}).catch((error) => {
next(error);
});
} else {
// For non-async interceptor functions
// Resetting json to original to avoid cyclic call.
// Custom logic/code.
response.json = oldJSON;
return oldJSON.call(response, finalResponse);
}
}
} catch (error) {
next(error);
}
}
在Server.js
文件中,注册中间件:
// Server.js file
import externalResponseFilter from "./middleware/response.filter.js:";
// Create Express server
const app = express();
// Response interceptor - Initialization.
app.use(externalResponseFilter);
并且在您 return 使用 response.json()
函数而不是 response.send()
的 response
、return 的控制器中。
如果需要任何额外的解释,请告诉我。
我认为您的情况不需要中间件,除非您需要对此路由进行身份验证检查。中间件具有在收到您的响应之前处理某些事情的功能。
您的代码应为:
router.get('/list',(req,res,next)=>{
Student.find().then(data=>res.json(data)).catch(err=>conole.log(err)) });
我想创建一个中间件来自动格式化我的输出,returns它的格式看起来像
{
"successful": "true",
"message": "Successfully created",
"data": {
"name": "Joe",
"year": 1
}
}
目前我只是返回数据本身的 json(名称、年份等)
我要添加"successful"、"message"等
下面是我的一些代码片段:
routes/student.js
var student_controller = require('../controllers/studentController');
router.get('/list', student_controller.student_list);
controllers/student.js
var Student = require('../models/student');
exports.student_list = function(req, res, next) {
Student.find()
.exec(function(err, list_students) {
if (err) {return next(err);}
res.json(list_students);
});
};
app.js
var studentRouter = require('./routes/student');
app.use('/student', studentRouter);
我如何制作这个中间件,我应该在哪个文件中调用它?
可以通过覆盖 response.json
函数来拦截响应。通过这样做,并添加我们的custom function
,每次调用response.json()
,我们的拦截功能就会被触发。
middleware/response.filter.js:
// Response Interceptor Middleware
export default (request, response, next) => {
try {
const oldJSON = response.json;
response.json = (data) => {
// For Async call, handle the promise and then set the data to `oldJson`
if (data && data.then != undefined) {
// Resetting json to original to avoid cyclic call.
return data.then((responseData) => {
// Custom logic/code. -----> Write your logic to add success wrapper around the response
response.json = oldJSON;
return oldJSON.call(response, responseData);
}).catch((error) => {
next(error);
});
} else {
// For non-async interceptor functions
// Resetting json to original to avoid cyclic call.
// Custom logic/code.
response.json = oldJSON;
return oldJSON.call(response, finalResponse);
}
}
} catch (error) {
next(error);
}
}
在Server.js
文件中,注册中间件:
// Server.js file
import externalResponseFilter from "./middleware/response.filter.js:";
// Create Express server
const app = express();
// Response interceptor - Initialization.
app.use(externalResponseFilter);
并且在您 return 使用 response.json()
函数而不是 response.send()
的 response
、return 的控制器中。
如果需要任何额外的解释,请告诉我。
我认为您的情况不需要中间件,除非您需要对此路由进行身份验证检查。中间件具有在收到您的响应之前处理某些事情的功能。 您的代码应为:
router.get('/list',(req,res,next)=>{
Student.find().then(data=>res.json(data)).catch(err=>conole.log(err)) });