Express.js Tutorial: Serving HTML in Express App (Lecture 2)

Posted by

Learn Express.js | Lecture – 2: Serving HTML in Express App

Welcome to the second lecture of our Learn Express.js series. In this lecture, we will learn how to serve HTML files in our Express.js application.

Setting up Express.js

Before we begin, make sure you have Express.js installed in your project. If not, you can install it using npm:

npm install express

Next, create a new file called app.js and require Express:

const express = require('express');

Create an instance of the Express application:

const app = express();

Serving HTML files

To serve HTML files in our Express app, we can use the express.static middleware to serve static files such as HTML, CSS, and JavaScript. First, create a new directory called public in your project’s root folder and place your HTML file inside it.

In your app.js file, add the following line to serve the static files:

app.use(express.static('public'));

This will serve the HTML file at the root URL of your application. If you have an index.html file in the public directory, you can access it in your browser at http://localhost:3000/index.html (assuming your server is running on port 3000).

Routing to HTML files

If you want to serve an HTML file based on a specific URL, you can use the app.get method to define a route:

app.get('/about', (req, res) => {
res.sendFile(__dirname + '/public/about.html');
});

In this example, when a user visits /about in their browser, the about.html file will be sent as the response.

Conclusion

Congratulations! You have learned how to serve HTML files in your Express.js application. This is a fundamental aspect of web development, and by mastering this, you can create powerful and dynamic web applications.

In the next lecture, we will learn about handling form submissions in Express.js. Stay tuned!