Serving Images in Express NodeJs
If you are building a web application using NodeJs and Express, you may want to serve images to your users. Serving images in Express NodeJs is a simple task, and in this article, we will show you how to do it.
Create a public directory
First, you need to create a directory in your project called “public” where you will store your images. You can do this using the following command:
mkdir public
Store images in the public directory
Once you have created the public directory, you can store your images in it. Make sure to use descriptive file names for your images to make them easier to refer to in your code.
Set up Express to serve static files
In your NodeJs application, you will need to tell Express to serve static files from the public directory. You can do this using the following code:
app.use(express.static('public'));
This line of code tells Express to serve static files from the public directory. Now, any files in the public directory, including images, will be accessible to users visiting your website.
Referencing images in your HTML
Once you have set up Express to serve static files, you can reference your images in your HTML using the following code:
<img src="/image.jpg" alt="Description of image">
Replace “image.jpg” with the actual file name of your image. When a user visits your website, the image will be loaded from the public directory thanks to the setup you did in your NodeJs application.
Conclusion
By following the steps outlined in this article, you can easily serve images in your Express NodeJs application. This is an essential aspect of web development, and with the right setup, you can provide a seamless user experience by delivering images efficiently.