When Using Express.js, What Should I Write In The src Attribute In Our Images Tags?
Accessing images in Express.js is very simple. The images are stored normally in the public/images
folder. The syntax we use to get them in our HTML is:
Syntax
<img src="/images/<image-name>" alt=""/>
Example
<img src="/images/person.jpg" alt="person"/>
Where is the name of the file including the image file ending(e.g. jpg, png). You do not need to include the word "/public"
in the filepath.
For example, let me demonstrate how to add the image of an orangutan.
We will be calling this image orangutan.jpg
.
I will be added the image to the folder /images
as shown below:
After dropping the image inside, the public/images
folder should look like this:
And in views/index.ejs
:
We use the following code to access the image file.
<img src="images/orangutan.jpg" alt="Orangutan"/>
Example
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<img src="images/orangutan.jpg" alt="Orangutan"/>
</body>
</html>