简体   繁体   中英

Node Express.js set route as a variable

I was wondering if there's a way to do this or if it can be done at all:

In express.js I've created a route:

app.get('/hello', (req, res) => {
  // Do stuff here
});

This about works but I was wondering if it's possible to add a variable instead:

app.get('/' + myVariable, (req, res) => {

  // so then I can do with the res of myVariable:

  if (res = 'something') {
     // do something
  } else if (res = 'somethingelse') {
    // do something else
  }

  //or use SWITCH CASE ...

});

If there a way to do something like this?

This could be done with Route paramerers .

app.get('/:myVariable', (req, res) => {
  const myVariable = req.params.myVariable;

  if (myVariable = 'something') {
     // do something
  } else if (myVariable = 'somethingelse') {
    // do something else
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM