【问题标题】:Express.js - Filter a number and a string in the URLExpress.js - 过滤 URL 中的数字和字符串
【发布时间】:2013-03-06 00:55:03
【问题描述】:

我想知道是否可以在查询本身中检查 Express.js URL 查询的特定格式(正则表达式)(无需输入回调。)

具体来说,我想执行不同的操作,具体取决于查询 URL 是字符串还是数字(如用户 ID 和用户名):

app.get('/:int', function(req, res){
    // Get user info based on the user id.
}

app.get('/:string', function(req, res){
    // Get user info based on the user name.
}

我可以在app.get的第一个参数中过滤数字吗,或者除了在回调中进行测试之外是不可能的:

/(\d)+/.test(req.params.int)
/(\w)+/.test(req.params.string)

【问题讨论】:

    标签: node.js filter express


    【解决方案1】:

    您可以用括号为命名参数指定模式:

    app.get('/:int(\\d+)', function(req, res){
        // Get user info based on the user id.
    }
    
    app.get('/:string(\\w+)', function(req, res){
        // Get user info based on the user name.
    }
    

    【讨论】:

    • 我不知道 express 可以做到这一点。这是在哪个版本中引入的?
    • 伟大的乔纳森。您能否向我们提供链接或文档以了解更多信息。谢谢。
    • 它目前不是一个有据可查的功能,但您可以在源代码中找到它:utils.pathRegexp(...)replace 中的 capture 参数是它的定义方式。
    【解决方案2】:

    快速路由器也接受正则表达式作为第一个参数。

    app.get(/(\d+)/, function(req, res, next) {})
    app.get(/(\w+)/, function(req, res, next) {})
    

    【讨论】:

    • 感谢 Floby,但是如何将查询参数用作回调的变量?在您的解决方案中,我只能过滤 URL,但不能使用查询值。
    猜你喜欢
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2018-12-18
    相关资源
    最近更新 更多