How do I automatically add a slug to my url in nodejs when using template

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. 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.

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. I can’t leave it like this because as I said before, I have a lot of products.

Here’s my js code

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

[
{
        "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"
            }
        }
    }
]

You get to do everything when you use express, including converting things to slugs, as opposed to Django and Rails which has that builtin (more or less). You need to pick a slug calculating library from npm, add the code to calculate slugs when you add datat, modify your records to hold the slug, and then look at URL construction with parameters (req.params) in express (nothing wrong with query parameters either). Once you have everything available in express it’s just a matter of providing the template with the appropriate data. You also really need to look into a better data store (a MongoDB springs to mind here) than a JSON file because that will be unwieldy once things hit production (typically you would create a product editing page in your app to add/edit products instead of operating on a file or DB directly).

I would look at the Back End, Quality Assurance, and Information Security projects here to get some more background on building out an express app or look at the MDN tutorial.

Good luck.

Sorry to trouble you but I’m still somewhat of a beginner so I’m not very familiar with the npm. Could you please recommend one and also show me a sample of how it would work? If it’s not a problem that is.
Thanks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.