Home > front end >  Express routes middlewares does not work outside of a class
Express routes middlewares does not work outside of a class

Time:10-10

For some reason (I suspect this is involved in this) when I add routes outside the Server class and make a request to it, the route ignores the middlewares. Is there a solution for this??

I am aware that I can put the routes inside the Server class and everything would work fine, but I need it to work this way.

this little example represents my original problem pretty well

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 WORKS */
      res
        .status(200)
        .send(`WORKING: Here is your body ${JSON.stringify(req.body)}`);
    });

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

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);

https://codesandbox.io/s/wonderful-sun-6uiyik?file=/index.js:0-1238

CodePudding user response:

You add your /post2 handler before calling init so the middleware's are registered after that route. Order matters here, it means the request won't go to the middlewares first.

Try splitting the server start and load middleware into two separate functions, so you can register your handler after the middleware, but before server start.

However as another commenter said, the class isn't really needed and not the normal way of composing routes in express. Still...

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);
  • Related