仅在url中显示没有id的产品slug

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了仅在url中显示没有id的产品slug相关的知识,希望对你有一定的参考价值。

我有一个分类列表,当用户点击一个分类时,它会将它们带到详细信息页面。我只想在url中插入slu ::

https://someshop.com/red-bag

我能够做到这一点,但问题是产品名称不是唯一的,因为不止一个用户可能想要在某个时候添加“红色包”。所以,我所做的是使用ID和slug,例如:

https://someshop.com/4d35c2fcef9b6c17167ff53y/red-bag

但这看起来并不特别好。有没有办法仍然检查ID,但实际上没有在网址中显示它?

html href:

<a href="/products/<%= product._id %>/<%= product.titleSlug %>" class="listing-item-container">

路由器:

router.get('/products/:productId/:titleSlug', shopController.getProductDetail);

控制器:

exports.getProductDetail = (req, res, next) => {
    const titleSlug = req.params.titleSlug;
    const productId = req.params.productId;
    Product.findOne({titleSlug: titleSlug, _id: productId})
    .then(product => {
        res.render('shop/product-detail', {
            pageTitle: 'Product detail',
            path: '/products',
            product: product
        });
    })
    .catch(err => {
        console.log(err);
    });
};
答案

我想说你最好的选择是根据从用户收到的title字符串并使用你选择的slug库来控制服务器端的slug。然后你可以检查你现有的条目,并确保你的slug是独一无二的 - 最坏的情况你只需要添加一些东西:你可以有/red-bag/red-bag-1等。仍然比UUID好。

以上是关于仅在url中显示没有id的产品slug的主要内容,如果未能解决你的问题,请参考以下文章

在 WordPress 管理列帖子/产品自定义帖子类型中显示 Slug

在 URL 中显示类别 Slug 而不是 ID

Symfony 5 - 在类别 url 中显示 id 和 slug 并在更新 slug 时通过 id 找到它

在没有在模型中定义的情况下在 rails 中创建 slug

通过其 slug 获取 WooCommerce 产品类别的 id

仅在特定产品变体属性中显示Woocommerce购物车中的消息