是否有可能在 express JS 中只接受路径变量中的两个值之一?

问题描述 投票:0回答:2

假设我的 REST 服务中有这个 GET url:

router.get('/api/platform/:type', async (req, res) => {
    // something
}

如果

:type
是“windows”或“android”,我只想要请求。有没有办法在 url 定义中做到这一点?

我想我以前见过这样的东西:

router.get('/api/platform/:type{windows|android}', async (req, res) => {
    // something
}

类似的东西,但对我来说不太管用。

javascript regex express rest url
2个回答
1
投票

您可以将正则表达式附加到路由参数以验证其格式:

router.get('/api/platform/:type(windows|android)', async (req, res) => {
    // something
}

为了更好地控制路由参数可以匹配的确切字符串,您可以在括号 (()) 中附加正则表达式:

Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}

https://expressjs.com/en/guide/routing.html


1
投票

您可能会使用正则表达式:

router.get(/\/api\/platform\/(?:windows|android)/, async (req, res) => {
  // something
}

参见路径示例;类型:“正则表达式”


这里是原生 JS 中的正则表达式示例,用于测试路由表达式:

const route =/\/api\/platform\/(?:windows|android)/;

const requests = [
  '/api/platform/windows',
  '/api/platform/android',
  '/api/platform/macos',
  '/api/platform/linux'
];

console.log(requests.filter(request => route.exec(request)));

© www.soinside.com 2019 - 2024. All rights reserved.