Express js built-in middleware

Express js built-in middleware

 

Hey!. In this article, we are going to talk about express js built-in middleware. If you are totally new in this, I recommend you check out my last articles on express js middleware by simply navigating to the node js section on this blog.

From the word built-in, you can understand this middleware doesn’t need any installation and hence comes with express by default. On this blog, we are going to look at two different built-in middleware which are express.static () and express.json ().

Today, we will learn about the express.static () middleware. Express static middleware is responsible or used to serve static files or static assets such as a webpage, files, images, style sheets, …

This is very useful in the sense, when ever you include a static asset like images, stylesheet etc in your app, express first checks the folder holding static resources or files.

It is mostly named the “public” folder for best practices and I also think its conventional. Whenever express finds a public folder in your app, it first checks the resources in that folder before coming to the response you sent to a route.

Let’s look at this perfect simple example:

In your project folder, add a folder with name public. In the public folder, add a html file with name index.html. 

server.js

Express js built-in middleware



Express js built-in middleware



OUTPUT
Express js built-in middleware


Express js built-in middleware


1. Notice that on opening the home route, the file, express checks the public folder and serves the html page rather than sending the response in the route handler.

2. Also notice that image source is found in the public folder.

3. Try removing the index.html file from the folder and start the server again, then refresh the page and tell me the results 

Thanks for reading. You can always drop your comments or questions. In our next article, we will learn how to use Express JSON built-in middleware.

Shalom!๐Ÿ’–

Ask Question #trycoder
Blog๐Ÿ‘‰ https://bit.ly/3p5GK4x
Facebook Page๐Ÿ‘‰ https://bit.ly/3o688OF
Twitter๐Ÿ‘‰ https://bit.ly/2LNwmAb
Watch more videos here
Click to SUBSCRIBE to more Videos!

Please Like, Comment, Share and Subscribe THANK YOU!

0 Comments