node.js - 使用来自 URL 参数的信息解析 URL
问题描述
我在工作中遇到了一个 Node.js 项目,但我不是 Node 开发人员。我的第一个任务是从 URL 参数解析 url 到商店。这是需要发生的事情:
原始 URL 包含 URL 参数“siteName”,如下所示:
https://example.com/s/Store/?siteName=SLUG
上面带有参数的 url 然后将解析为
https://example.com/s/Store/SLUG
该项目在 Express ^4.3.0 上运行。
我一直在深入研究 Node 文档,但我什至不确定从哪里开始。
解决方案
我建议你看看Express
您的问题的解决方案很简单。首先,您需要建立一个中间件来监听 /s/Stores 路由的请求。然后解析查询参数并获取 siteName 键的值。最后使用 res.redirect 方法运行 /s/Store/SLUG 路由的逻辑。
解决方案看起来像
app.get('/s/Stores', (req, res, next) => {
const query = req.query;
const siteName = query.siteName;
res.redirect('/s/Stores/' + siteName);
});
app.get('/s/Stores/:siteName', (req, res, next) => {
const siteName = req.params.siteName;
if (siteName === 'SLUG') {
// do something
}
// do something else
});
推荐阅读
- python - 单元测试多个子类
- list - 如何根据 list.length 限制小部件生成
- r - 使用 tidyverse 列出变量类型
- python - Matplotlib 百分比计算错误
- supercollider - Supercollider:对一个组应用 FX 似乎会影响其他组
- html - 通过单击隐藏和显示移动内容并在桌面上显示 3 列
- ios - 在表格视图单元格中时,如何根据其内容快速设置 CollectionView 高度?
- javascript - React Native 状态不更新
- bash - 在 bash 中将兆比特转换为千比特
- google-chrome - 单击页面中的任意位置时,Chrome 将我送回 Elements 选项卡