Home > other >  Can I dynamically generate routes path based on a database table property in express?
Can I dynamically generate routes path based on a database table property in express?

Time:01-30

I was trying to fetch data from permission table and give a route path depending on the data. Let assume I have a permission table where in slug property I saved a path url. Then I want to find those url and write them in my routes path. I am trying in this way but can't get the desired result. enter image description here

Is there any way I can achieve this?

CodePudding user response:

You can try something like this.

const express = require('express')
const app = express()


const routes = ['/users', '/posts', '/comments']

routes.forEach(route => {
    app.get(route, (req, res) => {
        res.send({ message: `Hello from route ${route}` })
    })
})

app.listen(8080, "localhost", () => {
    console.log("Hello from server")
})

CodePudding user response:

With the logic what @wiredmartian gave and by debugging I got the solution. So my first mistake was that calling my routes in async function which was pending during the call and I was returning router and exporting the async function. So, after debugging I found out these and here is the solution.enter image description here

  •  Tags:  
  • Related