Setting Up a Node.js Server with Express

Setting Up a Node.js Server with Express

Photo by Growtika on Unsplash

Node.js, with its non-blocking I/O and event-driven architecture, has become a popular choice for building scalable and performant web applications. When combined with Express.js, a minimalist web framework for Node.js, you can quickly set up a robust server to handle HTTP requests and build RESTful APIs. In this article, we'll walk through the steps to set up a Node.js server using Express.

Access the Code on GitHub

Feel free to explore the complete code for this setup on GitHub: Node.js Express Server Setup.

Prerequisites

Before diving into the setup process, ensure the following prerequisites are met:

  1. Node.js and npm: Download and install the latest version of Node.js from the official website: https://nodejs.org.

  2. npm or Yarn: Choose either npm or Yarn as your package manager. If you prefer Yarn, you can install it by following the instructions on the official website: https://yarnpkg.com.

Step 1: Create a New Project

Open your terminal and navigate to the directory where you want to create your project. Run the following command to initialize a new Node.js project:

This command creates a package.json file with default values.

Step 2: Install Express

Next, install Express as a dependency for your project. Run the following command:

This command installs Express and adds it to your project's node_modules directory.

Step 3: Create an Express App

Create a new file, let's call it app.js, and open it in your preferred code editor. Import Express and create an instance of the app:

Step 4: Define Routes

Express uses routes to handle different HTTP requests. Define a simple route to handle a GET request. Add the following code to your app.js file:

This code sets up a route for the root path ('/') and sends a "Hello, World!" response when accessed.

Here, req represents the request object containing information about the HTTP request, and res is the response object used to send a response to the client.

Step 5: Start the Server

To start the server, add the following code at the end of your app.js file:

This code specifies that the server should listen on port 3000 (you can choose a different port if needed) and log a message to the console when the server starts.

Step 6: Run the Server

Save your app.js file and run the following command in your terminal:

Visit http://localhost:3000 in your web browser, and you should see the "Hello, World!" message.

Congratulations! You've successfully set up a Node.js server with Express. This is just the beginning, and you can now explore more advanced features of Express, such as middleware, routing, and working with databases, to build powerful web applications.