Skip to content
Advertisement

How to retrieve data in front end from res.send and create page for each element in DB dynamically

I’ve got a variable, say data containing data in the form of an Array with each item having a unique ID.

app.get('/products/:id', function (req, res) {
  res.send(data.map(data => "" + data.id + "")) //basically gets the data of the element in the Array whos Id has been given to the server. 
})

I have sent the data from the server to the front-end on a GET request. But how do I create a seperate webpage for each element dynamically in the data array? where do i have to write the html and the css? I want a way with which I can create a page for each element like domain.com/products/id which displays information about the data entry which matches the Id . Do need to use pug? hbs?ejs? I’ so confused.

Advertisement

Answer

So I found I had to use Javascript Templates to send data to a view. I used ejs, which went pretty good!

Here’s how it went:

1. fetch my data form my DB, which in this case is MongoDB using db.findOne().

2. We get an array, let’s say data. send the variable to my view using the same res.render syntax, just in a cooler way.

app.get('/blogs/:id',(req,res)=>{
     const data = //find function
     res.render('page.ejs', {body:data});
})

:id creates a page for every element in the DB. and now the view that is, the public/page.ejs file has a global body variable, which we can now use to show our blogs.

3. the front end markup in pages.ejs:

<div class="blogs">
<%=body.forEach (item)=>{%>
<p><%=item.blog%></p><br>
<%=}%>
</div>

We call a forEach function on the array, and create a paragraph element for each item in the array, that is for each blog.

Please not that <%, <%= and %> are EJS’ tags. Read about them more in the official docs.

Thanks Mohammad for letting me know about this. (From comments)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement