如何在 Express.js 中传递 URL 中的字符串列表

Gia*_*nis 5 node.js express postman

为了在 URL 中传递单个参数,我在 Postman 中使用以下命令:

http://localhost:3000/api/prices/:shopId

这样可行!

现在,我想做的是将 shopId 替换为ShopIds 列表

我对如何实现这一点有什么想法吗?


伪代码:

URL for shopId = 1: http://localhost:3000/api/prices/1

URL for shopId = 2: http://localhost:3000/api/prices/2

我应该怎么做才能在单个 API 响应中同时获取 shopId 1 和 2?

Mad*_*ard 6

最好的办法是传递数组元素,并用不会出现在任何单词中的字符(例如逗号)分隔。

以这个片段为例:

app.get('api/prices/:ids', function(req, res){
    var ids = req.params.ids.split(',');
    console.log(ids); //['shopId1', 'shopdId2']
})
Run Code Online (Sandbox Code Playgroud)

您通过 GET 请求到达的端点:

http://localhost:3000/api/prices/shopId1,shopId2