首页 > 解决方案 > 如何检查两个 URL 是否指向相同的路径?

问题描述

我正在构建一个 URL Shortener,并且我决定尽可能回收短 ID 以节省数据库中的空间。如何检查 2 个 URL 是否指向相同的路径?

例如,假设用户为https://google.com/.

我的应用程序生成以下短 id:jkU3

因此,如果此用户访问https://tiny.url/jkU3我的快速服务器,则会将访问者重定向到https://google.com/.

这就像一个魅力,但知道让我们想象另一个人访问https://tiny.url/并为https://google.com. 另一个来为 生成一个短 URL https://www.google.com/,另一个来为 生成一个短 URL https://www.google.com。你明白了..

到目前为止,我的应用程序会浪费 4 个短 ID。

我怎样才能防止这种情况发生?有这个正则表达式吗?

这是我用于生成短 URL 的当前代码:

app.post("/", (req: Request, res: Response) => {
  const shortUrl: string = nanoid(4);
  const destination: string = req.body.destination;

  UrlSchema.create({
    _id: mongoose.Types.ObjectId(),
    origin: shortUrl,
    destination: destination,
  }).then(() => {
    // Unique Id
    res.json(shortUrl);
  });
});

标签: node.jsregexmongodbexpressmongoose

解决方案


在创建新条目之前,您可以检查工作目的地

const existing = await UrlSchema.findOne({destination:req.body.destination});
if(!existing){
    // create new
} else{
    // return same
}

这样,如果目标尚不存在,您将创建它。如果存在以更好地匹配 URL,您可以删除 tariling 斜杠 (/),


推荐阅读