Is it possible to implement a route within a controller in Express.js?

In my controller, I currently have the following code:

module.exports.validateToken = (req, res, next) => {
    const token = req.cookies.jwt;
    //console.log(token);
    if (!token) {
        return res.sendStatus(403);
    }
    try {
        const data = jwt.verify(token, "secret token");
        console.log(data);
        req.userId = data.id;
        return next();
      } catch {
        return res.sendStatus(403);
      }
  };

This code is then used by a route like this:

router.get("/secure-route", authController.validateToken, (req, res) => {
    return res.json({ user: { id: req.userId, role: req.userRole } });
  });

I am now trying to retrieve the JSON response from that route in a different controller but haven't been successful so far. Any suggestions?

Answer №1

To improve code reusability, I recommend extracting the response to a separate function:

// Define a function that returns data without directly sending it in the response
function protectedRoute(req) {
    return {user: {id: req.userId, role: req.userRole}};
}

router.get("/protected", authController.authToken, (req, res) => {
    // Use the function to generate the response
    return res.json(protectedRoute(req));
});

// Ensure that the middleware is still executed
router.get("/other_route", authController.authToken, (req, res) => {
    // Reuse the function to fetch the response from /protected
    const protectedResponse = protectedRoute(req);
    // Perform operations with the response
});

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

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

The function 'Message.Create' cannot be implemented in the Sequelize CLI

I have added mysql sequelize to my project and created a Message Model using the sequelize command, which generates both the model and migration files. I have also provided the database credentials in the config.json file. Now, when trying to insert a reco ...

Creating a Node Express API with a key value structure for parameters: step-by-step guide

I am able to adhere to the recommended express format, as shown below: api.com/users/:id However, I am required to align it with the current api pattern, which is: api.com/users?id=id ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

Executing the callback function

I am facing a situation where I have a Modelmenu nested within the parent component. It is responsible for opening a modal window upon click. Additionally, there is a child component in the same parent component that also needs to trigger the opening of a ...

Encountered an error "Not Found" when attempting to establish an AJAX connection between Javascript and Rails

I'm having an issue with a simple Rails controller method. When I call it from JavaScript as an AJAX method, I get the error message "Not Found" in the JavaScript error log, even though the method works fine when accessed directly in the browser. What ...

Translating Encryption from Javascript to Ruby

I have an application which utilizes HTML5 caching to enable offline functionality. When the app is offline, information is stored using JavaScript in localStorage and then transmitted to the server once online connectivity is restored. I am interested in ...

concealing the upper header while scrolling and shifting the primary header upwards

Is there a way to use CSS to move the main header navigation, including the logo and links, on my website up when scrolling down in order to hide the top black bar header that contains contact information? The website in question is atm.truenorthmediasol ...

What is the best approach to dynamically enable or disable a button depending on the state of multiple checkboxes in React.js?

Incorporated within a page is a component responsible for displaying multiple checkboxes and toggles. Located at the bottom of this component is a button labeled confirm, designed to save modifications and initiate a backend update request. A new functio ...

The controller utilizes inversify-restify-utils to interact with an empty context and the body

I am currently trying to use inversify-restify-utils, but I have encountered a problem. The request context and body variables are coming up empty. Here is my controller: @Controller('/users') @injectable() export class UsersController implement ...

Maintain MUI Autocomplete in the open state even after making a selection from the

Whenever I select certain options on my Autocomplete component, I want to keep the component open. However, each time I click on onChange, the Autocomplete closes automatically and I can't seem to find a way to prevent this. Is there a workaround? In ...

Express route parameter regex repetition

Looking to create a route where the foo parameter must be a positive integer, restricted by a regular expression using the * star repeat function: app.get('/foo/:foo([1-9][0-9]*)', fooHandler); This setup successfully matches the URL /foo/10, b ...

When working with a set of objects, consider utilizing jQuery's InArray() method to effectively handle

Within my Javascript code, I am working with an array of Calendar objects. Each Calendar object contains an array of CalendarEvent objects. Every CalendarEvent object holds properties for Date and Name. I am looking to determine if a specific date exist ...

jQuery does not change the scroll position of elements

I'm looking to implement a feature on my website where certain points act as "magnets" and when the user is near one of these points, the window automatically scrolls to the top. I found a jQuery plugin that does something similar which you can check ...

What is the reason behind Express not including a body parser in its bundle?

While I grasp the inner workings of body-parser, I find it baffling that such a basic functionality is not included by default in Express. It seems rather unnecessary, considering how fundamental this feature is. Why does Express require body-parser to r ...

Why isn't my Jquery click event able to download the csv file?

Initially, I was able to export a csv file using the html onclick element. However, when I switched to a jquery click event, the functionality stopped working. I don't understand why, as I believe the same function is being called. The Export.Expor ...

The POST function isn't functioning correctly within the temp.js file

My issue with the post method: var newUser = { "user5" : { "name" : "john", "password" : "qwerty123", "profession" : "developer", "id": 5 } } app.post('/createUser', function (req, res) { // Reading existing use ...

"Despite using the setHeader function in express.js to set a cookie, an empty cookie is still being

customer: <a href="http://localhost:3001/user/login">Login</a> server: const token = jwt.sign({ broadcasterId: user.twitchId }, process.env.JWT_SECRET); res.writeHead(301, { "Location": "http://localhost:3000" ...

When using React / Next.js, the .map() function may not rerender the output based on changes in the state array if the keys remain the same

In my react component, Matches.js, I handle the display of tournament matches sorted by rounds. The data is fetched from a parent component through nextjs SSR and passed as props to the child component. To avoid unnecessary requests upon data changes like ...

Simple CSS for creating a "red alert badge" with a number count

Looking for the best way to display the popular red notification indicator with count in a consistent manner across various browsers. It seems tricky to achieve a design that looks seamless on all platforms, as different browsers interpret paddings differe ...