Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to optimize an Express.js route?
    text
    copied!<p>I'm developing a reserved area that has the follow few pages:</p> <pre><code>/dashboard /dashboard/profile /dashboard/user /dashboard/view </code></pre> <p>that's a simple user control panel. At the moment i have four routes:</p> <pre><code>app.all('/dashboard', function(req, res, next) { /* Code */ }); app.all('/dashboard/profile', function(req, res, next) { /* Code */ }); app.all('/dashboard/user', function(req, res, next) { /* Code */ }); app.all('/dashboard/view', function(req, res, next) { /* Code */ }); </code></pre> <p>I would like to optimize it because in each of the above routes i have to call this function at the beginning:</p> <pre><code>authorized(req, function(auth){ if (!auth) return next(errors.fire(403)); /* route code */ }); </code></pre> <p>This function checks if the user is logged, so i need to call it on every reserved page.</p> <p>I would do something like:</p> <pre><code>app.all('/dashboard/*', function(req, res, next) { authorized(req, function(auth){ if (!auth) return next(errors.fire(403)); res.render(something, {}) }); }); </code></pre> <p>the <code>something</code> inside the res.render call has to be the view (page) I need to open. </p> <p>I want to call it <strong>ONE</strong> time, to remove redundant code.</p> <p>That could be the home of the panel (if the user wants /dashboard) or the page (if the user wants a page inside /dashboard like /dashboard/profile) in the last case i need to render 'profile' view.</p> <p>(I have to do a check before pass the view to render(), because if someone try /dashboard/blablablabla it should be a problem.)</p> <p>Thank you</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload