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