首页 > 解决方案 > 使用来自 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 文档,但我什至不确定从哪里开始。

标签: node.jsexpress

解决方案


我建议你看看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
});

推荐阅读