node.js - 如何检查两个 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);
});
});
解决方案
在创建新条目之前,您可以检查工作目的地
const existing = await UrlSchema.findOne({destination:req.body.destination});
if(!existing){
// create new
} else{
// return same
}
这样,如果目标尚不存在,您将创建它。如果存在以更好地匹配 URL,您可以删除 tariling 斜杠 (/),
推荐阅读
- ios - Xcode 13 快速帮助窗口无法在自定义对象上启动
- javascript - 如何在 Express 中添加自定义错误消息
- mongodb - Mongodb-按键分组数组
- c++ - 类实例不保留数据
- network-programming - 是否可以使用原始 AF_PACKET 进行通信
- python - 用零值块简化块矩阵?
- flutter - 使用 Provider 替代 GetX ever() 方法
- java - 非空 android 视图上的 java.lang.NullPointerException
- security - URL 中的脚本或没有什么有害的担心?
- facebook-like - 一般来说,在 Reddit、YouTube 和 Facebook 等网站上通常如何处理喜欢和推荐?