Day 7 of Full Stack Web Dev Bootcamp: Introduction to Express.js (2024-06-26)

Posted by

Welcome to Day 7 of the Full Stack Web Development Bootcamp! Today, we will be diving into Express.js, a powerful web application framework for Node.js. Express.js simplifies the process of building dynamic web applications and APIs by providing a minimalistic and flexible set of features.

To follow along with this tutorial, make sure you have Node.js installed on your machine. You can install Node.js by visiting the official website at https://nodejs.org and following the installation instructions for your operating system.

Once you have Node.js installed, you can create a new project folder for our Express.js application. Open up your terminal and run the following commands:

mkdir express-app
cd express-app
npm init -y

Next, we will install Express.js as a dependency for our project. Run the following command in your terminal:

npm install express

Now that we have Express.js installed, let’s create a simple web server using Express.js. Create a new file in your project folder called app.js and add the following code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Intro to Express.js</title>
</head>

<body>
    <h1>Welcome to Express.js</h1>
    <p>This is a simple web server created using Express.js.</p>
</body>

</html>

In the code above, we are creating a basic HTML file with a heading and a paragraph. This will be the content that our Express.js server will serve to clients.

Now, let’s modify our app.js file to create a web server using Express.js. Add the following code to your app.js file:

const express = require('express');
const app = express();
const port = 3000;

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

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

In the code above, we are requiring the Express.js module and creating a new instance of the Express application. We then define a route for the root URL ('/') that will serve our index.html file when a client visits the root URL. Finally, we start the Express server and listen on port 3000.

To start your Express.js server, run the following command in your terminal:

node app.js

Visit http://localhost:3000 in your web browser, and you should see the content of your index.html file displayed on the screen.

Congratulations! You have successfully created a simple web server using Express.js. In future tutorials, we will explore more advanced features of Express.js and learn how to build full-fledged web applications and APIs.

Stay tuned for Day 8 of the Full Stack Web Development Bootcamp!