带有 Express JS 的 SEO 友好链接
SEO friendly links with Express JS
我正在尝试使用 Node + Express JS 构建一个博客网站。我想让它对 SEO 友好,因为目前博客的 links 正在使用数据库的 ID。例如:
localhost:3000/posts/1
但是,我想要一个像这样的link:
localhost:3000/posts/my-adventure/
我正在关注 dev.to 网站,我看到他们使用的 href 不是带有 id,而是带有文章名称。我在这里感到困惑,因为从性能角度来看,这似乎效率不高,因为必须按长字符串搜索数据库?
<a href="/djangostars/choosing-python-for-web-development-top-16-pros-and-cons-4c4k" id="article-link-185734" class="index-article-link" aria-label="Main Story" data-featured-article="articles-185734">
</a>
我想请您帮助我如何在我的应用程序中实现它。目前我正在使用这种类型的路线:
router.get("/:id", async (req, res, next) => {
const post = await db.query(
"SELECT * FROM posts WHERE id = ",
req.params.id
);
res.render("readPost", { title: post.title, post: post });
});
一种方式(我更喜欢这种方式)
将 'id' 附加到 URL 以使其唯一。 (比如 localhost:3000/posts/my-adventure-1/)
您的代码片段可能不会改变,除了数据库列类型(如果您使用了数字)
您可以使用 slugify.
另一种方式
router.get("/:slug/:id", async (req, res, next) => {
const post = await db.query(
"SELECT * FROM posts WHERE id = ",
req.params.id
);
res.render("readPost", { title: post.title, post: post });
});
https://medium.com/@thiscodeworks.com/implementing-url-slugs-on-express-node-js-5f5890431dea
我正在尝试使用 Node + Express JS 构建一个博客网站。我想让它对 SEO 友好,因为目前博客的 links 正在使用数据库的 ID。例如:
localhost:3000/posts/1
但是,我想要一个像这样的link:
localhost:3000/posts/my-adventure/
我正在关注 dev.to 网站,我看到他们使用的 href 不是带有 id,而是带有文章名称。我在这里感到困惑,因为从性能角度来看,这似乎效率不高,因为必须按长字符串搜索数据库?
<a href="/djangostars/choosing-python-for-web-development-top-16-pros-and-cons-4c4k" id="article-link-185734" class="index-article-link" aria-label="Main Story" data-featured-article="articles-185734">
</a>
我想请您帮助我如何在我的应用程序中实现它。目前我正在使用这种类型的路线:
router.get("/:id", async (req, res, next) => {
const post = await db.query(
"SELECT * FROM posts WHERE id = ",
req.params.id
);
res.render("readPost", { title: post.title, post: post });
});
一种方式(我更喜欢这种方式)
将 'id' 附加到 URL 以使其唯一。 (比如 localhost:3000/posts/my-adventure-1/)
您的代码片段可能不会改变,除了数据库列类型(如果您使用了数字)
您可以使用 slugify.
另一种方式
router.get("/:slug/:id", async (req, res, next) => {
const post = await db.query(
"SELECT * FROM posts WHERE id = ",
req.params.id
);
res.render("readPost", { title: post.title, post: post });
});
https://medium.com/@thiscodeworks.com/implementing-url-slugs-on-express-node-js-5f5890431dea