Table of Contents
1. Handling Image Storage
When uploading files, they are stored in the public/images
folder. Using req.file
allows you to see both the file location and name. Remember, file sizes are always measured in bytes.
2. Fetching Data from the Database
To retrieve data from the database, use the findAll()
method, similar to SQL’s SELECT * FROM blogs
:
blogs.findAll();
Here’s how you can implement it asynchronously in Express:
app.get('/', async (req, res) => {
const datas = await blogs.findAll();
res.render('home.ejs', { blogs: datas });
});
3. Rendering Data in EJS
After fetching the data, pass it to your EJS template for rendering:
res.render('home.ejs', { blogs: datas });
Use a forEach
loop to iterate over and display each blog:
<%- blogs.forEach(blog => { %>
<h2><%- blog.title %></h2>
<p><%- blog.content %></p>
<%- }) %>
4. Displaying Images in EJS
Incorporate images into your dynamic pages by using the relative paths stored in your database:
<img src="/images/<%- blog.image %>" alt="Blog Image">