How to configure dynamic routes with express.js

前端 未结 7 2391
Happy的楠姐
Happy的楠姐 2020-12-07 20:32

I have a route.js which looks like this:

module.exports = function(app) {

  app.get(\'/tip\', function(req, res) {
    res.render(\"tip\");
  });

  app.get         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 20:50

    Here is what I did to create dynamic APIs while I am in control over which API allows access to which methods. To maintain the APIs from now on, you can just edit the APIs array.

    const APIs = [
        {
            route: 'order',
            methods: ['get', 'post']
        },
        {
            route: 'item',
            methods: ['get']
        },
    ]
    APIs.forEach(api => {
        api.methods.forEach(method => {
            app[method]('/' + api.route, (req, res) => require('./routes/' + api.route)[method](req, res))
        })
    })
    

提交回复
热议问题