Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filters on express.js

I want to do a filter like rails before filter on express.js. I have a file named photo.js where I'm putting all my photo related routes on there. But I need to redirect user that is not authenticated on my system to the login page. I want to do an beforeFilter so then I dont need to put that logic in all my routes...

Thanks

like image 590
rizidoro Avatar asked Jan 06 '12 19:01

rizidoro


People also ask

What is filter in Nodejs?

The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.

Is Express JS SEO friendly?

EJS is SEO friendly. You can customise all core SEO elements of your page/app so the GoogleBot can crawl it. In the end it all depends on how good your technical/onsite SEO is.

Is Express js used for routing?

js server. The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.


2 Answers

If you want to keep everything in your photo.js file, I think a better approach is to use app.all and pass multiple callbacks (which work like middleware in routing) built into the app routing. For instance

app.all('/photo/*', requireAuthentication, loadUser);

app.get('/photo/view', function(req, res) {
   res.render('photo_view');
});

app.get('/photo/list', function(req, res) {
   res.render('photo_list');
});

Where requireAuthentication and loadUser are functions.

Take a look the documentation for app.VERB and app.all at http://expressjs.com/api.html#app.all

like image 163
Dave Jensen Avatar answered Sep 23 '22 08:09

Dave Jensen


There are extensions or higher-level frameworks like express-resource.

like image 21
tjholowaychuk Avatar answered Sep 21 '22 08:09

tjholowaychuk