简体   繁体   English

Node Express.js将路由设置为变量

[英]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: 在express.js中,我创建了一条路由:

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 . 这可以通过Route paramerers完成。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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