【问题标题】:fastify url regex with slashes用斜杠快速化 url 正则表达式
【发布时间】:2021-06-13 12:34:25
【问题描述】:

我想用这样的正则表达式定义一个 fastify url 路由

     fastify.get('/:myregex/products',{
                        schema: {
                            params :{
                                myregex : {
                                    type: 'string',
                                    pattern: '((\\w)+:(\\w)+)'
                                }
                            },
                            response: {}
                        }
                    },async (req, reply) => {
                      reply.send(req.params.myregex);
                    }
    });

如果我大摇大摆地尝试像/param1:value1/param2:value2/param3:value3/products 这样的网址,它会在/param1%3Avalue1%2Fparam2%3Avalue2%2Fparam3%3Avalue3/products 中翻译它,但如果我在浏览器中尝试我的字符串,我有一个 404 { "message": "Route GET:/param1:value1/param2:value2/param3:value3/products/products not found", "error": "Not Found", "statusCode": 404 }

我做错了什么?

fastify": "^3.9.2" 节点 v12.20.1

【问题讨论】:

  • 你得到 404 的 url 以 /products/products 结尾 -> GET:/param1:value1/param2:value2/param3:value3/products/products 是故意的吗?
  • 是的,问题在于查询字符串的长度

标签: node.js regex url routes fastify


【解决方案1】:

您无法以这种方式归档您需要的内容,因为您将路径参数 myregex 映射到 URL param1:value1/param2:value2/param3:value3,因为您的值中有斜杠 /,并且它被处理为 URL as the standard said

您需要将/ 更改为另一个字符,或使用通配符* 更改URL 模式:

const app = require('fastify')();

app.get('/:myregex/products', { schema: {} }, async (req, reply) => {
  reply.send(req.params);
})

app.get('/products/*', {
  schema: {
    params: {
      '*': {
        type: 'string',
        pattern: '((\\w)+:(\\w)+)'
      }
    }
  }
}, async (req, reply) => {
  reply.send(req.params);
})

app.inject('/param1:value1@param2:value2@param3:value3/products')
  .then(res => { console.log(res.json()); })
  .catch(err => { console.error(err) })

app.inject('/products/param1:value1/param2:value2/param3:value3')
  .then(res => { console.log(res.json()); })
  .catch(err => { console.error(err) })

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多