0

I'm a student and I'm doing my H.W.

My goal is, when I click an item, send its id through URL and deal with in node.js

For example,

http://localhost:3000/product/:2

is the url when I clicked the item which has '2' as its ID.

But I don't know how to deal with it in node.js.

app.get('/searched.html',async function(req,res){
    let db = await getDBConnection();
    let rows = await db.all('select * from items');
    await db.close();

    var output=new Array();
    var id =  new Array();
    var query = url.parse(req.url,true).query;

    if(query.productSearch=='All'||query.productSearch==''){
        for(let i=0;i<rows.length;i++){
            output.push(rows[i]['product_image']);
            id.push(rows[i]['product_id']);
        }   
    }else{
        for(let i=0;i<rows.length;i++){        
            if(rows[i]['product_category']==query.productSearch){
                output.push(rows[i]['product_image']);
                id.push(rows[i]['product_id']);
            }
        }
    }
    
    var output_send = JSON.stringify(output);
    var id_send = JSON.stringify(id);

    res.render('index',{
        data: output_send,
        data2 : id_send
    });
});

The code above is the code what I used to deal with query String.

I guess I can reuse it, but I don't know how to fix it appropriately.

Could you give me some hints?

1 Answers1

1

You can get parameter from url like this :

/product/2

app.get('/product/:id', async function(req, res) {
  const id = req.params.id; // output : 2
});
arnaud_h
  • 121
  • 5
  • I got it, but when I try to render('info', {}), the css file is not applied although I just copied the html header. *The original page is 'index'.ejs and I'm trying to open 'info.ejs' through render() function. – CodingDosaMooDosa Jun 06 '22 at 13:33