Regular Expression in Node.js Express Router

不想你离开。 提交于 2020-01-02 05:19:49

问题


I have tried to find a way to enter regular expression into an express routing URL and then access the variable portion of the URL through the request object. Specifically I want to route to the url "/posts/" + any number of digits. Is there a way to do this?

Examples:

/posts/54
/posts/2
/posts/546

回答1:


This should do it:

app.get('/posts/:id(\\d+)', function(req, res) {
    // id portion of the request is available as req.params.id
});

EDIT: added regex to path to limit it to digits




回答2:


I agree with Johnny, my only addition being that you can do this for any number of levels. For example:

app.get('/users/:id/:karma', function(req, res){
    //Both req.params.id and req.params.karma are available parameters.
});

You should also check out the express documentation: http://expressjs.com/api.html. The request section would probably prove quite useful to you.



来源:https://stackoverflow.com/questions/12123564/regular-expression-in-node-js-express-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!