简体   繁体   English

如何在 nodejs 中自动将 slug 添加到我的 url

[英]How do I automatically add a slug to my url in nodejs

I'm having templating issues.我遇到了模板问题。

I'm working on an online store and I'm using my json file, which has all the details about a product, to generate cards for each product.我在一家在线商店工作,我正在使用我的 json 文件(其中包含有关产品的所有详细信息)为每个产品生成卡片。 Because I have a lot of products, creating a page for each product is out of the question so I also have a template page to show more details on a product.因为我有很多产品,为每个产品创建一个页面是不可能的,所以我还有一个模板页面来显示产品的更多详细信息。 What I want is that whenever I click on a product card, it takes me to the template product page then replaces the dummy data with the data for the product.我想要的是,每当我单击产品卡时,它会将我带到模板产品页面,然后将虚拟数据替换为产品数据。 I also want to make the url for the template page /product/product-slug but when i use this method, I'm unable to change the dummy data.我还想为模板页面/product/product-slug制作 url 但是当我使用这种方法时,我无法更改虚拟数据。

I eventually found a way to change the dummy data but the only way I could do it was by using the query id to find the data so the url looks like /product?id=productId instead and I really don't know how to work around it.我最终找到了一种更改虚拟数据的方法,但我能做到的唯一方法是使用查询 ID 来查找数据,因此 url 看起来像/product?id=productId而我真的不知道如何工作周围。 I can't leave it like this because as I said before, I have a lot of products.我不能这样离开它,因为正如我之前所说,我有很多产品。

Here's my js code这是我的js代码

const fs = require('fs')
const url = require('url')
const express = require('express');
const app = express();

app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');

const replaceTemplate = (temp, product) =>{
    let output = temp.replace(/{%NAME%}/g, product.name);
    output = output.replace(/{%ID%}/g, product.id);
    output = output.replace(/{%FIRST%}/g, product.image.primary);
    output = output.replace(/{%SECOND%}/g, product.image.secondary);
    output = output.replace(/{%SLUG%}/g, product.slug);
    output = output.replace(/{%PRICE%}/g, product.price);
    output = output.replace(/{%M1NAME%}/g, product.materials.material1.name);
    // output = output.replace(/{%M2NAME%}/g, product.materials.material2.name);
    output = output.replace(/{%M1IMG%}/g, product.materials.material1.img);
    // output = output.replace(/{%M2IMG%}/g, product.materials.material2.img);

    return output;
}

const earrings = fs.readFileSync(`${__dirname}/views/earrings.html`,'utf-8');
const product = fs.readFileSync(`${__dirname}/templates/product.html`,'utf-8');

const tempCard = fs.readFileSync(`${__dirname}/templates/stud-cards.html`,'utf-8');

const data = fs.readFileSync(`${__dirname}/dev-data/earrings/studs.json`,'utf-8');
const dataObj = JSON.parse(data);

app.get('/product', (req, res) => {
    const { query, pathname } = url.parse(req.url, true)
    // // // const prod = url.parse(req.url, `http://${req.headers.host}`)
    // // // const prod = dataObj[]
    // // // const output = replaceTemplate(product, prod);
    // // console.log(req.params.slug)
    // // res.end(product);
    // res.render('product', {pro: req.params.slug});

    res.writeHead(200, {'Content-type': 'text/html'});
    const prod = dataObj[query.id];
    const output = replaceTemplate(product, prod);

    console.log(prod);
    res.end(output);
}); 

app.listen(7664);

console.log('Now the server is running in url: http://127.0.0.1:7664');
 

And this is what my json file looks like这就是我的 json 文件的样子

[
{
        "id": 0,
        "name":"Amethyst Flat Sphere Studs",
        "image":{
            "primary": "../img/products/earrings/studs/Amethyst Flat Sphere Studs/0_BirthstoneSphereStud_AmethystSphereStuds_February_YG_Hero.jpg",
            "secondary": "../img/products/earrings/studs/Amethyst Flat Sphere Studs/2_BirthstoneSphereStud_AmethystSphereStuds_February_YG_Hero_Stacked_1.jpg"
        },
        "slug":"amethyst-flat-sphere-studs",
        "price":"180.00",
        "materials":{
            "material1":{
                "name": "14k Yellow Gold, Amethyst",
                "img": "../img/products/color/Amethyst.png"
            } 
        }
    },
    {
        "id": 1,
        "name":"Aquamarine Flat Sphere Studs",
        "image":{
            "primary": "../img/products/earrings/studs/Aquamarine Flat Sphere Studs/0_BirthstoneSphereStud_AquamarineSphereStuds_March_YG_Hero.jpg",
            "secondary": "../img/products/earrings/studs/Aquamarine Flat Sphere Studs/1_BirthstoneSphereStud_AquamarineSphereStuds_March_YG_Hero_Stacked_1.jpg"
        },
        "slug":"aquamarine-flat-sphere-studs",
        "price":"200.00",
        "materials":{
            "material1":{
                "name": "14k Yellow Gold, Aquamarine",
                "img": "../img/products/color/Aquamarine.png"
            }
        }
    }
]

What you need to use is req.params which will give you access to the URL parameters.您需要使用的是req.params ,它可以让您访问 URL 参数。

app.get('/product/:productSlug', (request, response) => {
    request.params.productSlug; // this will give you the product slug
}

Read more about params , query , and body and determine which way is better for your usecase.阅读有关paramsquerybody的更多信息,并确定哪种方式更适合您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将我的 API 密钥添加到此 URL 以成功获取? - How do I add my API key to this URL for successful GET? ReactJS - 将 slug 添加到 url(前端中的动态 slug) - ReactJS - Add slug to url (dynamic slug in frontend) 当访问我网站的特定 url 时,如何自动最大化浏览器 window? - How do I automatically maximize the browser window when a specific url of my site is visited? 如何制作自己的简单社交媒体按钮来自动获取当前URL? - How do I make my own simple social media buttons that grab the current URL automatically? 如何自动更新我的页面以添加输入的内容? 我收到 TypeError - How do I automatically update my page to add what is inputted? I am receiving TypeError 如何在 NodeJS 中引用我的 MongoDB 数据,然后将其添加到 Discord.JS 消息中? - How do I reference my MongoDB data in NodeJS, and then add it to a Discord.JS message? 在 NodeJS + Express 中,如何自动删除 URL 'www'? - In NodeJS + Express, how to automatically remove URL 'www'? Javascript:如何自动打开已链接的 url 链接? - Javascript: How do I open url links automatically that are linkedin? 如何将可变内容添加到URL - How do I add a variable content into URL SvelteKit:如何进行基于 slug 的动态路由? - SvelteKit: how do I do slug-based dynamic routing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM