node.js 快速路由器 - :id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34095126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:36:50  来源:igfitidea点击:

Express router - :id?

node.jsexpress

提问by glog

Real simple question guys: I see a lot of books/code snippets use the following syntax in the router:

真正简单的问题:我看到很多书籍/代码片段在路由器中使用以下语法:

app.use('/todos/:id', function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

I'm not sure how to interpret the route here... will it route '/todos/anything'? and then grab the 'anything' and treat is at variable ID? how do I use that variable? I'm sure this is a quick answer, I just haven't seen this syntax before.

我不知道如何解释这里的路线......它会路由'/todos/anything'吗?然后抓住“任何东西”并处理变量ID?我如何使用该变量?我确定这是一个快速的答案,我之前没有见过这种语法。

回答by Rilke Petrosky

This is an express middleware.

这是一个快速中间件。

In this case, yes, it will route /todos/anything, and then req.params.idwill be set to 'anything'

在这种情况下,是的,它将 route /todos/anything,然后req.params.id将设置为'anything'

回答by Bilash

On your code, that is for express framework middleware, if you want to get any id in the server code using that route, you will get that id by req.params.id.

在您的代码中,即用于 express 框架中间件,如果您想使用该路由在服务器代码中获取任何 id,您将通过req.params.id.

app.use('/todos/:id', function (req, res, next) {
  console.log('Request Id:', req.params.id);
  next();
});

回答by Nir Levy

Yes, in your example youl get req.params.idset to 'anything'

是的,在你的例子中你会被req.params.id设置为“任何”

回答by Roshan

Route path: /student/:studentID/books/:bookId
Request URL: http://localhost:xxxx/student/34/books/2424
req.params: { "studentID": "34", "bookId": "2424" }

app.get('/student/:studentID/books/:bookId', function (req, res) {
  res.send(req.params);
});

Similarly for your code:

同样对于您的代码:

Route path: /todos/:id
Request URL: http://localhost:xxxx/todos/36
req.params: { "id": "36" }

app.use('/todos/:id', function (req, res, next) {
  console.log('Request Id:', req.params.id);
  next();
});