Reputation: 14750
I need to make a single middleware that will handle each response to web user. I try to make something like the following:
function ajaxResponseMiddleware(req, res, next) {
var code = res.locals._code || 200;
var data = res.locals._response;
res.json(code, data);
}
app.get('/ajax1', function(req, res, next){
// Do something and add data to be responsed
res.locals._response = {test: "data2"};
// Go to the next middleware
next();
}, ajaxResponseMiddleware);
app.get('/ajax2', function(req, res, next){
// Do something and add data to be responsed
res.locals._response = {test: "data2"};
res.locals._code = 200;
// Go to the next middleware
next();
}, ajaxResponseMiddleware);
The response is handled in ajaxResponseMiddleware function where I can add some default state for all my ajax responses.
One thing that I don't like in the approach above is the adding ajaxResponseMiddleware function in each route.
So what do you think about this approach? May you advise improvements or share your experience.
Upvotes: 2
Views: 1817
Reputation: 18956
middleware is just a function function (req, res, next) {}
var express = require('express');
var app = express();
// this is the middleware, you can separate to new js file if you want
function jsonMiddleware(req, res, next) {
res.json_v2 = function (code, data) {
if(!data) {
data = code;
code = 200;
}
// place your modification code here
//
//
res.json(code, data)
}
next();
}
app.use(jsonMiddleware); // Note: this should above app.use(app.router)
app.use(app.router);
app.get('/ajax1', function (req, res) {
res.json_v2({
name: 'ajax1'
})
});
app.listen(3000);
Upvotes: 5