Search code examples
node.jsexpressweb-applicationsmiddleware

Express middleware on folder mounted app


I have an Express.js application running on https://mydomain.tld/folder. It sets up the route middlewares with

app.use('/path', middleware)

but only the one for the '/' path is working properly. I'm guessing this is because Express is looking for requests on https://mydomain.tld/path instead of on https://mydomain.tld/folder/path.

How can I get Express to process the requests for https://mydomain.tld/folder/path (preferably without having to hard code the path)?


Solution

  • Using a router:

    // myRouter.js
    
    var express = require('express')
    var router = express.Router()
    
    router.get('/path', middleware)
    
    // other routes...
    
    module.exports = router
    

    Now you can use your router with the relative path you want:

    var myRouter = require('./myRouter')
    
    app.use('/folder', myRouter)