How to Load Static Files in Express

We created a blog application in the previous lesson, where the user can create, view, edit, and delete posts. However, we neglected a tiny detail. Notice that even though we successfully uploaded an image, it is not rendered in the views/post/show.pug template.

pug
1extends ../layout.pug
2
3block meta
4    title #{post.title}
5
6block content
7    h1 #{post.title}
8    div #{post.content}
9
10    a(href=`/posts/edit/${post.id}`) Edit this post

So, how can we add uploaded images in this case? It sounds like a simple task, but if you simply add a <img> tag and pass the image source like this:

pug
1img(src=`/${post.picture}`, alt="An image")

It will not work.

This is due to security reasons. Because by default, the users are not allowed to access the server's file system directly in the frontend, or any random user will be able to see the source code.

Loading images

However, there are some exceptions. For example, in this case, you need to allow the user to access the uploads directory in order to retrieve the images.

To do this, you must add the express.static() middleware.

index.js

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

šŸŽ‰ Create an Account šŸŽ‰