Lesson 1
Setting Up a Basic Express.js Server
Introduction and Goals

Welcome to your first lesson in Back-End Engineering with Express.js! Today, we're going to dive into the world of server-side development, a critical component of any web application. By understanding and setting up a basic Express.js server, you'll unlock the door that allows user browsers and your web application to communicate.

Express.js is a lightweight and efficient web application framework for Node.js that's loved by developers worldwide. It's perfect for building web applications and APIs, serving as the back-end part of the MEAN stack — namely MongoDB, Express.js, AngularJS, and Node.js. You'll get a lot of hands-on practice throughout this course. Remember, all the necessary libraries, like Express.js, are pre-installed on the CodeSignal IDE, so you don't need to worry about installation for now.

By the end of this lesson, you will be able to set up an Express.js server from scratch, understand how it operates, and see it in action.

Are you excited? Let's get started!

Getting to Know Express.js

Just as human societies cannot function without rules and structures, web development requires frameworks to organize code and streamline development. One such framework is Express.js, used for building web applications on top of Node.js.

Node.js is a runtime environment that lets us execute JavaScript code on the server side. When you wrap this with Express.js, it becomes much more straightforward and elegant to handle HTTP requests, manage routes, and deal with middleware functionalities.

Express.js is widely used on some of the internet's most popular websites, including IBM, Uber, and Twitter. This popularity is due to Express.js's flexibility, simplicity, and scalability.

In real-world applications, Express.js simplifies tasks such as user authentication, data retrieval, and serving static files, making it a go-to solution for many developers.

JavaScript
1const express = require('express'); 2const app = express();

In the example above, we first import the Express.js module using the require() function. We then create an instance of Express.js as an app by calling the express() function. This app object will be used to set up our server.

Express.js Syntax Basics

Like every language or framework, Express.js has its syntax. Luckily, Express.js's syntax is quite minimalistic, which makes it easy to use and understand.

A commonly used feature in Express.js is the concept of middleware. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.

JavaScript
1app.use((req, res, next) => { 2 console.log('Time:', Date.now()); 3 next(); 4});

In the example above, this middleware logs the time of the request to the console. Middleware is crucial in real-world apps for handling tasks like logging, user authentication, and parsing request bodies.

Setting up a Basic Express.js Server

Setting up a basic server with Express.js is simple and only takes a few lines of code. The server listens for requests and sends back responses.

JavaScript
1const express = require('express'); 2const app = express(); 3const port = 3000; 4 5app.get('/', (req, res) => { 6 res.send('Hello world!'); 7}); 8 9app.listen(port, () => { 10 console.log(`Server listening at http://localhost:${port}`); 11});

Let's understand the code above. We start by importing express and initializing our app. We then define a port that the server will listen to.

The get route handler listens for HTTP GET requests at the root path, /. When such a request is received, it responds with "Hello world!".

Finally, app.listen() starts up our server, making it listen for requests on the specified port. On launching the server, it logs a message to the console.

Interacting with the Server

A key part of a server's role is to handle HTTP requests that come from clients (like web browsers). The most common types of HTTP requests are GET and POST. A GET request is made when you type a URL in the browser or click a link, and a POST request is generally made when you submit a form.

With Express.js, we can set up route handlers to listen for requests at different URLs. In the server setup code above, we included a route handler for a GET request at the / route. Here’s how you can handle a POST request in Express.js:

JavaScript
1app.post('/submit', (req, res) => { 2 res.send('Data Received'); 3});

By running the code and going to http://localhost:3000 on your browser, you can see how the server responds with "Hello world!".

Reviewing the Express.js Server Code

Let's break down our server's code. The purpose of the server is to listen for requests and respond appropriately, usually providing some data in response.

JavaScript
1app.get('/', (req, res) => { 2 res.send('Hello world!'); 3});

In the code above, the server is set up to listen for GET requests on the root URL (/), often the homepage in web development terms. Whenever it gets a GET request on this URL, it responds by sending the text "Hello world!".

This is the most basic setup of an Express.js server. As we continue with the lessons, you'll learn about handling different types of HTTP requests, different URL paths, and responding with more than just a string.

Running the Server

Finally, with our server ready, let's start it up! Running a Node.js server is as simple as running a command in your terminal. After navigating to the directory of your server file in the terminal (let's say the file is named index.js), you just need to run node index.js. This starts your server, and it starts listening for connections. You can then use your web browser, type in localhost:3000 in the address bar, and bam — you're greeted with the "Hello world!" message we sent from our server!

Using Axios for HTTP Requests

To interact with our backend routes, we can use a popular library called Axios. Axios is a promise-based HTTP client for the browser and Node.js. It's easy to set up and use for sending requests to our routes. For example, to retrieve all todos, you can use a GET request.

Here's a simple example using Axios to perform a GET request. We'll assume this code is placed in a file called run.js:

JavaScript
1const axios = require('axios'); 2 3const serverUrl = 'http://localhost:3000'; 4 5// Making a GET request to the server's root endpoint 6axios.get(serverUrl) 7 .then(response => { 8 console.log('Response from the server:', response.data); 9 }) 10 .catch(error => { 11 console.error('Error while making GET request:', error.message); 12 });

In this example, axios.get sends a GET request to http://localhost:3000/. When the request is successful, it logs the response data to the console. If there's an error, it catches and logs the error. This makes it easy to interact with your backend routes and test them during development.

To execute the run.js file, open your terminal and enter the command node run.js. This will run the script with Axios requests and offer real-time insights into the server's operations.

Real-world Application and Takeaways

In the real world, web servers are responsible for handling much more than just a single root route. They handle several different types of routes, deal with user authentication, interact with databases to fetch and store data, manage file uploads, and much more. However, every web server — no matter how complex — is rooted in the fundamental concepts we've discussed today.

By setting up your Express.js server, you have taken the first but crucial step in back-end development with Express.js. Always remember that Express.js is all about handling different routes and serving various client requests through those routes — similar to guiding a friend visiting your hometown to the best places!

Lesson Summary and Practice

Great job getting to this point! Today we've learned about the Express.js web application framework and the Node.js platform it's built upon. We have delved into the world of server-side development, exploring the Express.js syntax and setting up a basic server.

In this lesson, we covered how to set up a basic Express.js server, handle GET requests as well as POST requests, and use middleware.

You have seen how to listen for HTTP requests, serve responses, and interact with the server using your web browser. You now understand the concept of routes and know how to handle GET and POST requests on different routes, and how to interact with them using axios library.

Below is the full code of this lesson for reference:

JavaScript
1// Importing the Express.js module 2const express = require('express'); 3 4// Creating an instance of the Express.js app 5const app = express(); 6 7// Defining the port that the server will listen on 8const port = 3000; 9 10// Middleware function to log the time of the request 11app.use((req, res, next) => { 12 console.log('Time:', Date.now()); 13 next(); 14}); 15 16// Defining a GET route handler for the root URL ('/') 17app.get('/', (req, res) => { 18 res.send('Hello world!'); 19}); 20 21// Defining a POST route handler for the '/submit' URL 22app.post('/submit', (req, res) => { 23 res.send('Data Received'); 24}); 25 26// Starting the server and making it listen for requests on the specified port 27app.listen(port, () => { 28 console.log(`Server listening at http://localhost:${port}`); 29});

Just like learning to ride a bike, the best way to understand servers and Express.js is to practice continuously. Upcoming exercises will allow you to hone these skills, enabling you to respond to different routes, manage varying request methods, and serve specific responses.

So, are we ready to get our hands on the code and lay the first stone toward becoming an Express.js pro? Let's hop on to the exercises!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.