Is there a method to consistently implement a controller function across all routes within a router file in Express?

I have the following code snippets within an application. I am looking for a way to apply "authController.isLoggedIn" to each instance of "router.get" without having to repeat it multiple times. Initially, I thought using router.use might be the solution, but upon further investigation, it does not seem to be the right approach. Any assistance on this matter would be highly appreciated. Thank you.

router.get('/tour/:slug', viewsController.getTour);
router.get('/login', authController.isLoggedIn, viewsController.getLoginForm);
router.get('/signup', authController.isLoggedIn, viewsController.getSignupForm);
router.get('/me', authController.protect, viewsController.getAccount);
router.get('/my-tours', authController.protect, viewsController.getMyTours);
router.get('/create', authController.protect, viewsController.createTour);

Answer №1

Perhaps you could try something along these lines:

const secureRoutes = (route, param, ...handlers) =>
  router.get(route, secureController[param], ...handlers);

router.get('/tour/:slug', viewController.displayTour);
secureRoutes('/login', 'checkAuth', viewController.showLoginForm);
secureRoutes('/signup', 'checkAuth', viewController.showSignupForm);
secureRoutes('/dashboard', 'protectRoute', viewController.viewDashboard);
secureRoutes('/my-tours', 'protectRoute', viewController.myToursList);
secureRoutes('/create-tour', 'protectRoute', viewController.createNewTour);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to Trigger Events on Selection

I have a unique situation: 1) One of my dropdown's choices features various car names. 2) Another dropdown has two options: When selecting each option in the second dropdown, the following should occur: a) Choose UserInput - This action will hide ...

Encountering an issue while attempting to access a specific endpoint in my node.js and express application

I recently created an API Rest to allow users to register, but I'm facing an issue where I cannot access the endpoint http://localhost:5000/api/user/register/. The error message "Cannot GET /api/user/register/" keeps popping up. Here is a snippet from ...

Is there a way to sort through a JSON object using JavaScript?

I have a JSON string that looks like this: { "Animal":{ "Cat":20, "Dog":10, "Fish":5 }, "Food":{ "Pizza":500, "Burger":200, "Salad" ...

Display information in a detailed table row using JSON formatting

I have set up a table where clicking on a button toggles the details of the corresponding row. However, I am having trouble formatting and sizing the JSON data within the table. Is there a way to achieve this? This is how I implemented it: HTML < ...

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...

What could be causing the partial to not load JavaScript properly?

Hello, I am a newcomer to Angular and I'm currently working on implementing the slick carousel. It functions properly on the index page, but when I try to use the same HTML in a partial and include it with ng-view, it doesn't work as expected. T ...

Encountering an issue with ReactJS + Redux where the error message states: "Error in prop type: The Right-hand side of 'instanceof' cannot be called"

Currently working on a web app project in React with Redux for global state management. A puzzling issue has arisen - we're receiving warnings in the browser console. How can we resolve this? It seems related to prop types declaration, but the soluti ...

Gathering Servlet details from non-form elements

I am currently in the process of developing an application that is capable of parsing JSON strings. At this stage, I am able to input a JSON string using Java, write it to an HTML document, and then have a JavaScript program read and parse it before ultima ...

What is the best way to retain user information through jwt even when the browser is closed?

My goal is to integrate json web token for user authentication in my expressjs, nodejs and angularjs app using jsonwebtoken and express-jwt. After reading several articles and tutorials on the topic, I have a few questions that have left me feeling a bit c ...

Creating a custom event for every reference within a Vuejs for loop

I'm working with a loop of data and have a modal for each iteration <div ref="vuemodal-{{loop.index}}"> Each modal is a bootstrap modal, and I want to bind an event to them that triggers whenever the modal is closed mounted(){ Obj ...

What method is best for deleting an item from the database in HTML structure - POST, GET, or XHR action?

I have a webpage that displays content in a table format and allows users to delete a specific row by clicking on it. The structure of my rows is as follows: foreach ($rewards as $reward) { echo '<tr id="' . $reward[&apos ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

Utilizing API calls within a loop using AngularJS

I need to execute a series of APIs in a loop, but I want the second loop to start only after receiving the result from the last API call in the first loop. How can I achieve this? for(var i=0; i<array.length; i++ ) service.getfunction(array[i]).t ...

After an Ajax request, the functionality of Javascript/Jquery ceases to work

After successfully submitting a form via ajax for the first time, the subsequent submissions seem to break all javascript functionality on the page. Additionally, the form is unable to submit with ajax again. Below is the code snippet for the ajax call: ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Executing multiple server-side methods on an AJAX call in ASP.NET MVC: A comprehensive guide

I am facing a situation where I have a method that is called by jQuery, and its result is displayed on a popup. Sometimes, it takes some time to complete and a blank popup appears with processing message. When clicking on close, the popup disappears but th ...

[Vue alert]: Component mounting failed due to usage of mixin with a parameter

For the past day, I've been facing difficulties creating a Vue mixin with a parameter. When attempting to do so, I encounter a [Vue warn]: Failed to mount component: template or render function not defined error. Below is my JS file which includes the ...

The request body is not defined within the Express controller

Currently facing an issue with my controller: when I use console.log(req), I can see all the content of the request body. However, when I try console.log(req.body), it returns as undefined. This problem arises while working on my Portfolio project with Nex ...

The React-Virtualized Autosizer component is returning a height value of 0 when used with VirtualScroll

Despite AutoSizer's width providing the correct value, I am consistently encountering a height of 0 for Autosizer. This is causing the VirtualScroll component to not display properly. However, when using the disableHeight prop and setting a fixed heig ...