node.jsexpresspassengerexpress-routerphusion

Express.js issues Router not working with phusion passenger Node.js


I have problems with Phusion Passenger and Express.js the router does not work and does not give me any kind of error

Try on a hosting with Node versions 16 and 14, as well as on a dedicated server with Node 16 (Cent OS)

Express version is: 4.18.2

const express = require("express");

const app = express();

const  router = express.Router();

// domain.com/backend/

app.use('/backend/test', (req, res) => {
  res.json({ message: 'test' })
})


app.get("/backend/test2", ({req, res}) => {
    res.json({ message: "test2" }) 
})

router.get("/backend/testrouter", ({req, res}) => {
    res.json({ message: "testrouter" }) 
})

router.get("/backend/testrouter2", ({req, res}) => {
  res.json({ message: "testrouter2" }) 
})

app.use((req, res) => {
  res.status(404).json({ message: 'error' });
});

app.listen(3000);

The first two endpoints work, while the last two do not work


Solution

  • You should use router as a middleware for app:

    const express = require("express");
    const app = express();
    const  router = express.Router();
    
    // domain.com/backend/
    
    app.use('/backend/test', (req, res) => {
      res.json({ message: 'test' })
    })
    
    app.get("/backend/test2", ({req, res}) => {
        res.json({ message: "test2" }) 
    })
    
    router.get("/backend/testrouter", ({req, res}) => {
        res.json({ message: "testrouter" }) 
    })
    
    router.get("/backend/testrouter2", ({req, res}) => {
      res.json({ message: "testrouter2" }) 
    })
    
    app.use(router) // <== add this line
    
    app.use((req, res) => {
      res.status(404).json({ message: 'error' });
    });
    
    app.listen(3000);