Here is a simple route:
// get all users
app.get('/api/user/get-all', authenticated.yes, function(req, res) {
queryUsers.findAllUsers( function( users ){
res.json( users );
} );
});
The output would be the json returned from the "queryUsers.findAllUsers" function.
This is great, but i want to route all my json output through something more rigid so the output would be:
res.json({
success: true,
payload: users
});
This is really easy to do manually but means I have to write this out each time which is a lot of typing.
Is it possible to add new functions to the "res" object, to enable something like this:
res.jsonSuccess( users );
and:
res.jsonFail( users );
Which would output
res.json({
success: true,
payload: users
});
and:
res.json({
success: false,
payload: users
});
respectively.
json() Function. The res. json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.
Simply put, you need to configure the timeout value on the HTTP Server that express generates when you call the listen method. For example: // create an express app const app = express(); // add a route that delays response for 3 minutes app. get('/test', (req, res) => { setTimeout(() => { res.
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
app. use((req, res, next) => { //next() or return next() }); In the function app. use((req, res, next), we have three callbacks i.e. request, response and next. So, if you want to use next() then simply write next() and if you want to use return next then simply write return next().
As loadaverage pointed out, middleware is how you do it. For some more specificity:
app.use(function(req, res, next) {
res.jsonFail = function(users) {
return res.json({
success: false,
payload: users
})
};
res.jsonSuccess = function(users) {
return res.json({
success: true,
payload: users
});
};
next();
});
and then this should work:
app.get("/my/route", function(req, res) {
return res.jsonSuccess(["you", "me"]);
});
Sometimes I want to extend current method with new method. For example, log everything that I sent.
This what you can do:
app.use(function (req, res, next) {
var _send = res.send
res.send = function (data) {
console.log('log method on data', data)
// Call Original function
_send.apply(res, arguments)
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With