在Mule中如何读取多个同名查询参数并获取对应值集合?
多值查询参数读取方案
针对URL https://localhost:8081/api/Location?Name=Germany&Name=America 里重复出现的Name查询参数,可以通过不同环境的内置工具直接读取为数组,无需手动拆分字符串。
浏览器前端环境
使用浏览器原生支持的URL和URLSearchParams接口,调用getAll方法即可获取同一参数名的所有值:
// 构造URL实例 const targetUrl = new URL('https://localhost:8081/api/Location?Name=Germany&Name=America'); // 读取所有Name参数值 const nameResult = targetUrl.searchParams.getAll('Name'); console.log(nameResult); // 输出 ["Germany", "America"] // 如果需要转为逗号分隔的字符串,调用join方法即可 const commaStr = nameResult.join(','); console.log(commaStr); // 输出 Germany,America
Node.js 后端环境
Node.js 10.x以上版本也支持和浏览器一致的URL和URLSearchParams接口,用法和前端示例完全相同。
原生模块旧版实现
使用Node.js内置的url模块解析,开启查询参数自动解析开关即可:
const url = require('url'); const parsedUrl = url.parse('https://localhost:8081/api/Location?Name=Germany&Name=America', true); const nameResult = parsedUrl.query.Name; console.log(nameResult); // 输出 ["Germany", "America"]
Express 框架实现
Express默认会自动把重复的查询参数解析为数组,直接读取即可:
app.get('/api/Location', (req, res) => { const nameResult = req.query.Name; console.log(nameResult); // 输出 ["Germany", "America"] res.send(nameResult.join(',')); // 直接返回逗号分隔的字符串 })
内容的提问来源于stack exchange,提问作者SH4444KO
相关产品推荐
相关产品推荐

