Express中有多个可选的路由参数? [英] Multiple optional route parameters in Express?

查看:473
本文介绍了Express中有多个可选的路由参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express处理 / articles /:year /:month /:day 格式的路由,其中​​年,月和日是可选的

I am using Express to handle a route which is in the format of /articles/:year/:month/:day, where year, month and day are optional.


  • 如果三个参数均未给出,则将返回所有文章;

  • 如果给定年份,则将退回该年的物品;

  • 如果给出年份和月份,将退回该年和月的物品;

  • 如果同时给出所有三个参数,则将返回该年,月和日的文章。

  • If none of the three params is given, all articles will be returned;
  • If year is given, articles of that year will be returned;
  • If year and month are given, articles of that year and month will be returned;
  • If all three params are given, articles of that year, month and day will be returned.

我的问题是,我该如何使它们可选?使用我定义的当前路由,除非所有三个参数都存在,否则它将无法解析,并且将属于默认路由。

My question is, how do I make them optional? With the current route I've defined, unless all three parameters are present, it will not be able to be resolved and will fall into the default route.

推荐答案

expressjs的指南用于路由提及:


Express使用 路径到正则表达式 ,用于匹配路由路径;有关定义
路由路径的所有可能性,请参见
到正则表达式的路径文档。 快速路线测试器是用于测试基本
快速路线的便捷工具,尽管它不支持模式匹配。

Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching.

基本上,您可以使用

/articles/:year?/:month?/:day?

这篇关于Express中有多个可选的路由参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆