Middleware in Express routes are only functional within a class

It seems that when routes are added outside the Server class, middleware is ignored when making requests. Is there a solution to this issue?

I understand that placing the routes inside the Server class would resolve the problem, but I specifically need it to function this way.

This example effectively illustrates the original problem:


const express = require("express");
const cors = require("cors");
const axios = require("axios");

class Server {
  constructor() {
    this.app = express();
  }

  loadMiddlewares() {
    this.app.use(cors());

    this.app.use((req, res, next) => {
      console.log("MIDDLEWARE WORKING!");
      next();
    });

    this.app.use(express.json());
  }

  init() {
    this.loadMiddlewares();

    this.app.post("/post", function (req, res) {
      /* MIDDLEWARES WORK */
      res
        .status(200)
        .send(`WORKING: Here is your body ${JSON.stringify(req.body)}`);
    });

    this.app.listen(3001);
    console.log("Server running");
  }
}

const server = new Server();

server.app.post("/post2", function (req, res) {
  /* MIDDLEWARES NOT WORKING */
  res
    .status(200)
    .send(`NOT WORKING: Here is your body 2 ${JSON.stringify(req.body)}`);
});

server.init();

setTimeout(() => {
  axios({
    url: "https://6uiyik.sse.codesandbox.io/post",
    method: "post",
    data: {
      hi: "HIII!!"
    }
  }).then((res) => console.log(res.data));

  axios({
    url: "https://6uiyik.sse.codesandbox.io/post2",
    method: "post",
    data: {
      hi: "HIII!!"
    }
  }).then((res) => console.log(res.data));
}, 1000);

Visit this link for code reference

Answer №1

Make sure to place your /post2 handler before calling the init function, as it ensures that the middleware is registered after the route. The sequence matters in this case because the request will not pass through the middlewares initially.

To address this issue, consider separating the server start and middleware loading into two distinct functions. This way, you can register your handler after the middleware but before starting the server.

It's worth noting, however, that using classes may not be necessary for composing routes in Express, although it still works...

const express = require("express");
const cors = require("cors");
const axios = require("axios");

class Server {
  constructor() {
    this.app = express();
  }

  loadMiddlewares() {
    this.app.use(cors());

    this.app.use((req, res, next) => {
      console.log("MIDDLEWARE WORKING!");
      next();
    });

    this.app.use(express.json());
  }

  loadRoutes() {
    this.loadMiddlewares();

    this.app.post("/post", function (req, res) {
      /* MIDDLEWARES WORKS */
      res
        .status(200)
        .send(`WORKING: Here is your body ${JSON.stringify(req.body)}`);
    });
  }

  listen() {
    
    this.app.listen(3001);
    console.log("Server runinng");
  }
}

const server = new Server();
server.loadRoutes()
server.app.post("/post2", function (req, res) {
  res
    .status(200)
    .send(`NOT WORKING: Here is your body 2 ${JSON.stringify(req.body)}`);
});

server.listen();

setTimeout(() => {
  axios({
    url: "https://6uiyik.sse.codesandbox.io/post",
    method: "post",
    data: {
      hi: "HIII!!"
    }
  }).then((res) => console.log(res.data));

  axios({
    url: "https://6uiyik.sse.codesandbox.io/post2",
    method: "post",
    data: {
      hi: "HIII!!"
    }
  }).then((res) => console.log(res.data));
}, 1000);

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

Controlling user login sessions and cookies with angular.js is essential for ensuring secure and seamless

I have a login application where I need to implement session and cookies using angular.js. Below is the code for my login functionality. loginController.js: var loginAdmin=angular.module('Channabasavashwara'); loginAdmin.controller('log ...

How can I decrease the size of a picker in React Native?

My example shows that the picker displays numbers, but the size of it is too long and covers the entire screen. I want to reduce its size. How do I do it? In this code, I have built a dropdown list picker that contains numbers 1-31. I tried to reduce the ...

Guide to incorporating WebElement scrolling in Selenium using Java?

I need to implement a scroll function for a table on my webpage rather than scrolling the entire page, so using window.scrollBy is not an option. After attempting to find the container responsible for the scroll functionality in the DOM (with no luck), I ...

What could be causing the malfunction of Bootstrap Multiselect functionality?

I have been attempting to set up Bootstrap Multiselect but it simply refuses to work. Despite trying various solutions, I am unable to pinpoint the issue. My index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...

Postpone the processing of a message in the Service Bus Queue until a specific time using NodeJS

Despite trying multiple tutorials, I have been unable to achieve the desired result so far. Currently, my setup involves a nodejs app that sends messages to the Service Bus Queue and another nodejs app that continuously polls it. The goal is to schedule a ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

Iterate through the pixels of the canvas to locate the x and y coordinates and position of each white pixel

In my project, I have a canvas with white text drawn on it. To identify the white pixels, I extract the image data and iterate through each pixel using the following code snippet: var pixelData = this.ctx.getImageData(0, 0, this.ctx.canvas.width, this.ctx ...

Beginner's guide to setting up and utilizing passport for various user types

Trying to articulate this question may prove challenging, but bear with me! In my Node and Express application, I've implemented Passport (Local) for authentication. Within the framework of my app, I must manage two user types: Application users: in ...

Exploring the power of makeStyles in Material UI when combined with TypeScript

I am currently in the process of converting a JavaScript template to Typescript. Here is an example of my accordionStyle.ts file: import { primaryColor, grayColor } from "../../material-dashboard-pro-react"; const accordionStyle = (theme?:an ...

What is the process for duplicating a group containing loaded .obj models?

Initially, I created a new THREE.Object3D() and named it groupChair. I then loaded 3 obj files and added them to groupChair within the callback function. After that, I added the groupChair to the scene and it worked perfectly. However, I encountered an iss ...

Assistance with JavaScript regular expressions for dividing a string into days, hours, and minutes (accounting for plural or singular forms)

My challenge is with handling different variations in a string var str = "2 Days, 2 Hours 10 Minutes"; When I use : str.split(/Days/); The result is: ["2 ", ", 2 Hours 10 Minutes"] This method seems useful to extract values like "days", "hours" and " ...

A guide on utilizing Node.js to showcase the chosen option value as a response

I'm a beginner with Node.js and Express My goal is to retrieve the selected option from an HTML select list and display it as a response using Node.js HTML Code <form name="survey" id="survey" method="post" action="/survey"> <select na ...

What causes the lack of impact on lambda rendering speed despite integrating webpack?

Hey there, I've been working on implementing webpack for a project that involves microservices, Node.js, TypeScript, AWS, and AWS SAM. My main objectives are: Reduce the cold start time of lambda functions. Minimize security vulnerabilities by e ...

Express route path does not match with query parameters

My code refers to the path as: Axios.get('/api/getUsersData/?location='+location+'&managerId='+managerId) and the routes is set up like this: router.get('/api/getUsersData/?location=:location&managerId=:managerId', ...

Utilizing Angular's ng-repeat directive to dynamically generate images, with the added functionality of attempting to

I am utilizing angular-drupal to fetch data from my backend built on Drupal. My objective is to create an image gallery using the default endpoints provided by the services module. I make a call to node load to retrieve a specific node, then I extract the ...

Encountering difficulty extracting information from JSON file within AngularJS factory

I am struggling with a Json file named discover.json located at json-files/discover.json {"data": [ {"username": "aky123", "name": "ajay"}, {"username": "sky123", "name": "sanjay"} ]} Below is my factory setup: var myAppServices=a ...

Leveraging jQuery within a webpack module shared across multiple components, located outside the webpack root directory

When working with multiple layouts that rely on shared typescript files, it is important to ensure these files are accessible across different layouts using webpack. While attempting to include jquery in my ajax.ts, I encountered the following error: ERR ...

Stop the flow of data in the RxJS stream depending on a specific value within the stream

I developed a straightforward component featuring a single button that initiates and halts a sequence of numbers generated by RxJS timer. import { Component, OnInit } from '@angular/core'; import { BehaviorSubject, Observable, timer, merge } fro ...

Conceal location labels in maps provided by tilehosting.com

I am currently in the initial stages of developing a maps web application and I want to incorporate maps from tilehosting.com along with the leaflet library (leafletjs.com). Overall, it seems to be working fine, but I'm struggling with hiding the def ...

Leveraging express while utilizing bodyParser.json()

I'm having trouble receiving the req.body when making a post request to an express server: var app = express(); app.use( bodyParser.json() ); app.post( '/push', function(req, res){ console.log('body', req.body); res.sendStatus ...