Nodejs, Express, routes - node.js

I have build an api using express. In my routes file I have:
app.route('/getBalances')
.post(api.getBalances);
api.getBalances, depending on a parameter send through post called "vehicle" gets first which is the correct controller to load and to invoke its getBalances method, in example:
var controller = commonModel.getController(query.vehicle.toLowerCase());
controller.getBalances();
getBalances is not the only entry point I have, so I was wondering if it was possible to call a "global" method which is call for every entry point, in that way I wouldn't need to identify the correct controller on each method but on the global method.
Thanks in advance for your help.

Use a preliminary middleware which will run before adding any api route. Example:
// This middleware has to be added first.
app.use(function(req, res, next) {
var query = req.query; // or `req.body`, whatever you like
if (query && query.vehicle) {
req.controller = commonModel.getController(query.vehicle.toLowerCase());
}
next(); // delegate request to the next routes
});
// Now add specific api middlewares.
app.route('/getBalances')
.post(function(req, res) {
var controller = req.controller; // we've populated this earlier
res.send(controller.getBalances());
});
app.route('/anotherMethod')
.post(function(req, res) {
var controller = req.controller;
// etc.
});

Related

In REST API, How to restrict URL access from browser using Nodejs & Expressjs

I have a MEAN stack application and using Node.js and Express.js as back-end API.
Assuming I have a 'comments' route as follow
/* GET /comments listing. */
router.get("/", function(req, res, next) {
Comment.find(function(err, comments) {
if (err) return next(err);
res.json(comments);
});
});
And use it in my server like this:
var commentsRouter = require('./routes/comments');
...
app.use('/comments', commentsRouter);
My question is: Is there a way to prevent users to access http://mrUrl/comments in browser and deny the request with probably 403 Forbidden message but at the same time JavaScript file tries to access the same URL will receive a content message (in the example should be res.json(comments);)
Also, would it be possible to enable such a restriction for all routes once, not for each.
Yes, you can use a middleware.
A middleware is a function you can pass before or after the main function you are executing (in this case, GET comments)
the order of the function location matters, what comes first - executes first, and you implement it like so:
app.use(myBrowsingRestrictionMiddlewareFunction) // Runs
app.use('/comments', commentsRouter);
app.use('/account', accountRouter);
You can also use within a route handler:
app.post('/comments', myMakeSureDataIsAlrightFunction, myMainCreateCommentFunction, myAfterStatusWasSentToClientAndIWishToMakeAnotherInternalActionMiddleware);
The properties req, res, next are passed into the function automatically.
which means, myBrowsingRestrictionMiddlewareFunction receives them and you can use them like so:
export function myBrowsingRestrictionMiddlewareFunction(req, res, next) {
if (req.headers['my-special-header']) {
// custom header exists, then call next() to pass to the next function
next();
} else {
res.sendStatus(403);
}
}
EDIT
Expanding regards to where to place the middleware in the FS structure (personal suggestion):
What I like to do is to separate the router from app.js like so:
app.js
app.use('/', mainRouter);
router.js
const router = express.Router();
router.use(middlewareForAllRoutes);
router.use('/comments', commentsRouter);
router.use(middlewareForOnlyAnyRouteBelow);
router.use('/account', accountRouter);
router.use(middlewareThatWillBeFiredLast); // To activate this, remember to call next(); on the last function handler in your route.
commentsRouter.js
const router = express.Router();
router.use(middlewareForAllRoutesONLYFORWithinAccountRoute);
route.get('/', middlewareOnlyForGETAccountRoute, getAccountFunction);
router.post('/', createAccount);

NodeJS - Send result of a database query to a view or route before render

I'm making a webapp with NodeJS using Express JS, Socket IO and Handlebars, but i am pretty new to these technologies.
I'm struggling to find a way to pass the result from a query to my menu(a partial), mainly because Node is async, so by the time the result from my query returns, the page has already rendered, and the values never passed.
main.handlebars (Main layout):
(...)
{{> menu}}
(...)
{{{body}}}
router.js
var express = require('express');
var router = express.Router();
var index_controller = require('../controllers/index_Controller');
router.get('/', index_controller.index);
module.exports = router;
index_controller.js
exports.index = function(req, res) {
res.render('main_page_html');
};
This menu will appear in every page, and i want to show in this menu names from people online, that it's the result from the query.
I tried putting the code for the query inside the route function, and it works, but i would have to copy the same code to every route that i have, because as i said, this menu appears in all of them.
If i try to do a function outside the route function, async kicks in and no data is sent to the page.
There's definitely a better solution for this.
P.s.: Emit my data via socket to the client is one way, but i would like to do things server-side.
-Solution-
I did as Tolsee said, i created a middleware, so now i can call this middleware in every route that is needed. This is how i have done:
menu.js
exports.onlineUsers = function (req, res, next) {
// database query {
// res.locals.onlineUsers = queryResult;
// next();
// }
}
router.js
var menu_midd = require('../middleware/menu');
router.get('/', menu_midd.onlineUsers, index_controller.index);
module.exports = router;
index_controller.js
exports.index = function(req, res) {
res.render('main_page_html', {data: res.locals.onlineUsers});
};
Well, at least works for me. :)
There are two solutions to this problem. If you want to do it server side then you need to pass the menu data to handlebar/view. If you want it through all the pages then you can make a middleware function and employ it to all the router like below:
function middleware(req, res, next) {
// your code
// define your menu variable
// And assign it to res.locals
res.locals.menu = menu
next()
}
// let's employ it to all the routes
app.use(middleware)
// You can employ it to separate routes as well
myRouter.get('/sth', middleware, function(req, res) {
// your code
})
With that being said, If your menu is showing online users, you will need to use socket.io(even if you rendered it through server-side at the start) because you will need to update the online user list in real-time.

Easiest way to pass variables to routes templates in Express?

I've just made an Node.js app modular by splitting up data models and routes into separate files.
My routes are exported by express.Router(). In these routes I would like to import queried values from my app.js to be rendered with the templates.
How would I in the easiest way save things lets say with app.locals or req.variableName?
Since the route using express.Router() ties it together with app.js, should I be using app.params() and somehow make these values accessible?
Using globals seems like a worse idea as I'm scaling up the app. I'm not sure if best practice would be saving values to the process environment either using app.locals.valueKey = key.someValue...
Big thanks in advance to anyone
If I understand the question correctly, you want to pass a value to a later middleware:
app.js:
// Let's say it's like this in this example
var express = require('express');
var app = express();
app.use(function (req, res, next) {
var user = User.findOne({ email: 'someValue' }, function (err, user) {
// Returning a document with the keys I'm interested in
req.user = { key1: value1, key2: value2... }; // add the user to the request object
next(); // tell express to execute the next middleware
});
});
// Here I include the route
require('./routes/public.js')(app); // I would recommend passing in the app object
/routes/public.js:
module.export = function(app) {
app.get('/', function(req, res) {
// Serving Home Page (where I want to pass in the values)
router.get('/', function (req, res) {
// Passing in the values for Swig to render
var user = req.user; // this is the object you set in the earlier middleware (in app.js)
res.render('index.html', { pagename: user.key2, ... });
});
});
});

Proper way to remove middleware from the Express stack?

Is there a canonical way to remove middleware added with app.use from the stack? It seems that it should be possible to just modify the app.stack array directly, but I am wondering if there is a documented method I should be considering first.
use actually comes from Connect (not Express), and all it really does is push the middleware function onto the app's stack.
So you should be just fine splicing the function out of the array.
However, keep in mind there is no documentation around app.stack nor is there a function to remove middleware. You run the risk of a future version of Connect making changes incompatible with your code.
This is a useful functionality if you are inheriting some unwanted middleware from a framework built on express.
Building on some of the answers that came before me: In express 4.x the middleware can be found in app._router.stack. Note that the middleware are invoked in order.
// app is your express service
console.log(app._router.stack)
// [Layer, Layer, Layer, ...]
Tip: You can search the individual layers for the one you want to remove/move
const middlewareIndex = app._router.stack.findIndex(layer => {
// logic to id the specific middleware
});
Then you can just move/remove them with standard array methods like splice/unshift/etc
// Remove the matched middleware
app._router.stack.splice(middlewareIndex, 1);
There seems to be no built in way to do that, but you can manage to get the same result with a small trick. Create your own array of middleware (let's call it dynamicMiddleware) but don't push that into express, instead push just 1 middleware that will execute all the handlers in dynamicMiddleware asynchronously and in order.
const async = require('async')
// Middleware
const m1 = (req, res, next) => {
// do something here
next();
}
const m2 = (req, res, next) => {
// do something here
next();
}
const m3 = (req, res, next) => {
// do something here
next();
}
let dynamicMiddleware = [m1, m2, m3]
app.use((req, res, next) => {
// execute async handlers one by one
async.eachSeries(
// array to iterate over
dynamicMiddleware,
// iteration function
(handler, callback) => {
// call handler with req, res, and callback as next
handler(req, res, callback)
},
// final callback
(err) => {
if( err ) {
// handle error as needed
} else {
// call next middleware
next()
}
}
);
})
The code is a bit rough as I don't have a chance to test it right now, but the idea should be clear: wrap all dynamic handlers array in 1 middleware, that will loop through the array. And as you add or remove handlers to the array, only the ones left in the array will be called.
You can use the express-dynamic-middleware to make this.
https://github.com/lanbomo/express-dynamic-middleware
Use it like this
const express = require('express');
// import express-dynamic-middleware
const dynamicMiddleware = require('express-dynamic-middleware');
// create auth middleware
const auth = function(req, res, next) {
if (req.get('Authorization') === 'Basic') {
next();
} else {
res.status(401).end('Unauthorization');
}
};
// create dynamic middleware
const dynamic = dynamicMiddleware.create(auth);
// create express app
const app = express();
// use the dynamic middleware
app.use(dynamic.handle());
// unuse auth middleware
dynamic.unuse(auth);
No way of removing a middleware as far as I know. however, you can assign a boolean flag to 'deactivate' a middleware at anytime you want.
let middlewareA_isActivate = true;
// Your middleware code
function(req, res, next) {
if (!middlewareA_isActivate) next();
// .........
}
// Deactivate middleware
middlewareA_isActivate = false;
EDIT :
After reading through ExpressJs (4.x) code, I notice that you can access the middlewares stack via app._router.stack, manipulation goes from there I guess. Still, I think this 'trick' might not be able to work in future Express
P/s: Not tested how Express behaves when manipulate the middlewares stack directly though
Following from the hints above, I've add success with the following on express 4.x. My use case was logging what was coming in with Slack Bolt, so I could capture and then mock it:
// Define a handy function for re-ordering arrays
Array.prototype.move = function(from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
// Use the normal use mechanism, so that 'extra' stuff can be done
// For example, to log further up the order, use app.use(morgan("combined"))
app.use([my-middleware]);
// Now adjust the position of what I just added forward
const numElements = app._router.stack.length;
app._router.stack.move(numElements - 1, 1);
You can use
console.log("Stack after adjustment", app._router.stack)
to confirm the new order is what you want. (For Slack Bolt, I had to use app.receiver.app because the Bolt app wraps the express app.)
We can write like this.
// route outside middleware
route.get("/list", (req, res)=>{
res.send("from listing route");
});
//use middleware
router.use(Middlewares.AuthMiddleware.isValidToken);
//routes inside the middleware
route.post("/create", (req, res)=>{
res.send("from create route");
});
route.delete("/delete", (req, res)=>{
res.send("from delete route");
});
So basically, write routes before injecting middleware into your route.

How to put middleware in it's own file in Node.js / Express.js

I am new to the whole Node.js thing, so I am still trying to get the hang of how things "connect".
I am trying to use the express-form validation. As per the docs you can do
app.post( '/user', // Route
form( // Form filter and validation middleware
filter("username").trim()
),
// Express request-handler gets filtered and validated data
function(req, res){
if (!req.form.isValid) {
// Handle errors
console.log(req.form.errors);
} else {
// Or, use filtered form data from the form object:
console.log("Username:", req.form.username);
}
}
);
In App.js. However if I put something like app.get('/user', user.index); I can put the controller code in a separate file. I would like to do the same with the validation middleware (or put the validation code in the controller) to make the App.js file easier to overview once I start adding more pages.
Is there a way to accomplish this?
Basically I would like to put something like app.get('/user', validation.user, user.index);
This is how you define your routes:
routes.js:
module.exports = function(app){
app.get("route1", function(req,res){...})
app.get("route2", function(req,res){...})
}
This is how you define your middlewares:
middlewares.js:
module.exports = {
formHandler: function(req, res, next){...}
}
app.js:
// Add your middlewares:
middlewares = require("middlewares");
app.use(middlewares.formHandler);
app.use(middlewares...);
// Initialize your routes:
require("routes")(app)
Another way would be to use your middleware per route:
routes.js:
middlewares = require("middlewares")
module.exports = function(app){
app.get("route1", middlewares.formHandler, function(req,res){...})
app.get("route2", function(req,res){...})
}
I hope I answer your questions.
You can put middleware functions into a separate module in the exact same way as you do for controller functions. It's just an exported function with the appropriate set of parameters.
So if you had a validation.js file, you could add your user validation method as:
exports.user = function (req, res, next) {
... // validate req and call next when done
};

Resources