Middleware applied universally across all methods rather than exclusively to those defined within the controller

I created a controller with a single function that acts as a callback for the `GET /user/ request:

class UserController {
  async getAllUserData(req, res) { /* retrieve data and return response */ }
  async changePassword(req, res) { /* update password and return response */ }
}

const ctrl = new UserController();

api.get('/user', middlewareA, ctrl.getAllUserData);
api.post('/changePassword', ctrl.changePassword);

export default api;

Everything is working smoothly, where the middleware is only applied to the GET /user route. However, my goal was to apply middleware to all functions within a single controller file and implement this at the level of my index.js file, like so:

/* initialization... */

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Token');
  res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  next();
});

app.use(middleware, UserController);

app.listen(3000, () => {
  console.log('Example app listening on port 3000!');
});

However, in the second code snippet, since I placed the middleware before UserController, it gets applied to all methods - including the OPTIONS requests sent by browsers - even though UserController only has two methods using GET and POST.

Why does the middleware from the second snippet affect all methods? Do I need to add it separately to each function in every controller?

Answer №1

When using express, the order in which you chain elements with app.use() is crucial. Here is a breakdown of what happens in the second code snippet:

  1. The request begins
  2. The header middleware is executed
  3. Your custom 'middleware' (defined before UserController) is run
  4. UserController is called
  5. Route middleware is triggered
  6. A response is sent back

It's important to understand that both middleware and route middleware are essentially the same thing, and they will execute in the order specified by app.use().

In your code, you can either assign middleware as shown in the first snippet, or you can handle URLs within the middleware itself. Another approach is to group related URLs together.

app.use('/example', middleware);
app.use('/example', UserController);

// ........
api.get('/example/user', middlewareA, ctrl.getAllUserData);
api.post('/example/changepassword', ctrl.changepassword);

For more detailed examples, refer to the express documentation.

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

Utilize the power of checkboxes in Vue.js and Quasar framework to enable specific functionalities upon being

There are two checkboxes available: 'Show Active' and 'Show Live'. Initially, the 'Show Live' checkbox is disabled. I need a feature where if 'Show Active' is checked, it will enable the 'Show Live' checkb ...

Node.Js server not executing socket function

As a JavaScript enthusiast starting out with learning sockets through Node JS, I have encountered an issue that I can't seem to resolve. My client successfully connects to the server without any errors, but when emitting commands from the client side, ...

Issue with displaying custom in-line buttons in JQGrid

Currently, I am utilizing jqgrid 3.8.2 (I am aware it's not the latest version, but I plan on updating it soon after seeking some advice :-)) I have successfully incorporated a couple of in-line buttons into my jqgrid using the default formatter &apo ...

Is it possible to create a multi-module setup using Loopback models integrated with loops?

I'm just starting out with the loopback framework and I'm planning to have a large number of models in my application. My goal is to organize them into different folders, such as: ./server/models/frontend/user/user.js ./server/models/frontend/us ...

Updating the vue data map to group items by both date and employee

I am currently facing an issue with my Vue component and template where I display employees along with their hours/scans by date. The problem is that the current mapping aggregates all hours and scans based on the first record's date. The challenge a ...

Tips for sending an API request from a local Ionic server to a separate local Express server

I currently have two applications running on my local machine: an ionic2 app running on http://localhost:8041 and an express app running on http://localhost:8000. Using Angular 2 observables, I am encountering an issue when making API calls with absolute p ...

How to resolve the error "TypeError: this.props.state is not a function in React

I'm struggling to figure out what's wrong with my code snippet here. I've been searching for the error message on google, but I just can't seem to grasp the issue. componentDidMount() { fetch('http://192.168.1.33:8080/getproje ...

Is it common for all my components to become class components when I integrate Redux into ReactJS?

During my experience with learning react, my instructor consistently emphasized the importance of using functional components whenever possible, and advised to limit the use of class components. It seemed straightforward at the time. However, now that I a ...

Problem encountered when attempting to pass data from parent to child component

While using Vuu.js, I encountered an issue with passing a value from parent to child component. Initially, I had it working perfectly with a provided example. However, as soon as I tried changing the name, the functionality broke. I'm struggling to un ...

Continuously receive data from a reactive socket

My current approach involves using this code to receive data from sockets: socket.on('send_image', (message) => { setImage(message.image) console.log(message) }) The server is constantly sending data (images from camera ...

Locating the Searchbox on Google Maps with the angular-google-maps library

I am currently working on positioning the Google Maps searchbox variable in a way that allows it to stay fixed under markers as they are listed. I am utilizing the Angular Google Maps library for this purpose, which provides a directive known as <ui-g ...

Experiencing an "ENOTFOUND" error after attempting to make a large volume of API calls, possibly in the range of 100,000, to maps.google

I have a requirement to send a large number of requests to https://maps.googleapis.com/maps/api/place/queryautocomplete/json. Currently, I am fetching lists of strings from multiple files and sending requests to the mentioned API. When I test with 100 str ...

My Ajax request is hitting a snag - the success function isn't functioning as expected

Having an issue with the success function in my ajax call. It doesn't seem to be working as expected. Check out the code snippet below: var data1 = { "name": namedata[0], "email": namedata[1], "mobile": namedata[2], "company": namedata[3], "message" ...

Error 504: Gateway Timeout - Issue with Node.js + Express + PostgreSQL Server

In my tech stack, I am utilizing node + express for the backend, postgresql for the database, and EJS for the front-end rendering. For managing the server start/stop/logs, I have incorporated the pm2 package. At times, when encountering an API query erro ...

Challenges with Page Loading in Selenium

Inquiry: When a URL is accessed in a web browser, the page begins to load. A loading symbol appears at the top, and once it stops, our selenium script continues with the next steps. However, there are instances where the page takes longer to load all its ...

"Enhancing user experience with keyboard navigation using JavaScript

As a graphic designer, not a web developer, I am in the process of creating my portfolio website and would appreciate your patience. I am hoping to navigate between projects on my website using arrow keys on the keyboard. To implement this functionality, ...

encountering a problem with permissions while attempting to update npm

Has anyone encountered a permission error with npm when trying to update to the latest version? I recently tried updating npm and received this error message. I'm unsure of how to resolve it. Any suggestions? marshalls-MacBook-Air:Desktop marshall$ n ...

Adjust the size of the image based on its current dimensions, rather than its original dimensions

My goal is to scale an image with the ID "room" by a parameter of +1 or -1, which represents +-10% of the constant scaling factor. This is my current approach: function scalar(scaleP100){ /* scaleP100 ranges from +1 to -1 */ var addX ...

The functionality of sending a list of objects with a file via AJAX to an ASP.NET controller is failing to

Currently, I am working on ASP.NET Core and I need to send a list of objects containing files from an Ajax request to the controller. For more details, the object I want to send includes a file. You can view an image here. ViewModel public class FormDat ...

Interactive feature allowing all embedded YouTube videos on a webpage to play synchronously, with sound disabled, and on a continuous loop

I am in the process of developing a button that, when clicked by a user, will trigger all embedded YouTube videos on a specific webpage to start playing simultaneously, with sound muted, and set to loop. The target page for this button implementation can ...