与Express JS的SEO友好链接
我正在尝试使用Node + Express JS建立博客网站。我想使其对SEO友好,因为当前到博客的链接正在使用数据库的ID。例如:
localhost:3000/posts/1
但是,我想要一个这样的链接:
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 = $1",
req.params.id
);
res.render("readPost", { title: post.title, post: post });
});
回答如下:一种方法(我喜欢这个)
将'id'附加到URL以使其唯一。 (例如localhost:3000 / posts / my-adventure-1 /)
您的代码段可能不会更改,除了db列类型(如果您使用过数字)除外>]
您可以使用slugify。
另一种方式
router.get("/:slug/:id", async (req, res, next) => { const post = await db.query( "SELECT * FROM posts WHERE id = $1", req.params.id ); res.render("readPost", { title: post.title, post: post }); });
https://medium/@thiscodeworks/implementing-url-slugs-on-express-node-js-5f5890431dea