Day 1: Setting Up a Node.js and Express Server


In this tutorial, you’ll learn how to set up a basic Node.js server using the Express framework. Express is a popular and lightweight web framework for Node.js that makes it easy to build APIs and web applications. By the end of today’s lesson, you’ll have a basic RESTful API running on your local machine.


What You Will Learn Today:

  1. Installing Node.js and Express
  2. Setting up a basic Express server
  3. Creating your first API route
  4. Running the server and testing the API with Postman

Step 1: Install Node.js

Before starting, you need to have Node.js installed on your machine. If you haven’t already installed Node.js, follow these steps:

  1. Go to the official Node.js website.
  2. Download and install the LTS (Long-Term Support) version for your operating system.
  3. After installation, verify that Node.js and npm (Node Package Manager) are installed by running the following commands in your terminal:
node -v
npm -v

You should see version numbers for both Node.js and npm.


Step 2: Create a New Node.js Project

Once Node.js is installed, the next step is to create a new Node.js project.

  1. Open your terminal or command prompt and navigate to the folder where you want to create your project.
  2. Run the following command to create a new directory for your project:
mkdir my-express-api
cd my-express-api
  1. Initialize the Node.js project by running the following command:
npm init -y

This will create a package.json file in your project directory with default settings. The package.json file keeps track of your project’s dependencies and scripts.

See also  Here are the steps to send the file to someone using mutt in the command line:

Step 3: Install Express

Now, let’s install Express, which will serve as the foundation for building our RESTful API.

  1. Run the following command to install Express:
npm install express

This will install Express and add it to your package.json file under dependencies.


Step 4: Create a Basic Express Server

Now that Express is installed, let’s set up a basic Express server.

  1. In the root of your project, create a new file called index.js. This file will serve as the entry point for your Node.js server.
  2. Open index.js in a code editor and add the following code:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;

// Basic route for the home page
app.get('/', (req, res) => {
  res.send('Welcome to my Express API!');
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Explanation:

  • const express = require('express'): This imports the Express framework.
  • const app = express(): This creates an instance of an Express application.
  • app.get(): This sets up a basic route that responds to HTTP GET requests. In this case, when someone visits the root URL (/), the server will respond with "Welcome to my Express API!".
  • app.listen(): This starts the server on the specified port (5000 by default), and when the server starts, it logs a message to the console.

Step 5: Running the Server

Let’s run the server and make sure everything is working.

  1. In your terminal, start the server by running:
node index.js

You should see the following message in the terminal:

Server is running on port 5000

This means your Express server is up and running.

See also  Day 8: Implementing Deep Linking in React Native

Step 6: Testing the API with Postman

Now that the server is running, you can test your API. We will use Postman, a popular tool for testing APIs.

  1. Download and install Postman if you don’t have it already.
  2. Open Postman and follow these steps:
  • Select New Request.
  • Set the method to GET.
  • In the URL field, enter: http://localhost:5000.
  • Click Send.

You should see the response Welcome to my Express API! in Postman, which confirms that the server is working properly.


Step 7: Creating a Simple API Route

Let’s expand on this by creating a simple API route. We’ll set up a new route to handle user data.

  1. In index.js, add the following route:
// Route to get user data
app.get('/api/users', (req, res) => {
  const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
    { id: 3, name: 'Alice Johnson' }
  ];

  res.json(users); // Send the list of users as a JSON response
});

Explanation:

  • app.get('/api/users'): This creates a new route that listens for HTTP GET requests at /api/users.
  • res.json(): This sends the list of users as a JSON response.
  1. Save the changes and restart the server by running node index.js again.
  2. Test the new route in Postman by entering http://localhost:5000/api/users as the URL and clicking Send.

You should receive the following JSON response:

[
  { "id": 1, "name": "John Doe" },
  { "id": 2, "name": "Jane Smith" },
  { "id": 3, "name": "Alice Johnson" }
]

This confirms that you’ve successfully created your first API route!


Step 8: Recap and Summary

Congratulations! You’ve successfully set up a Node.js server using Express and created your first API route. Here’s a quick summary of what you’ve done:

  • Installed Node.js and Express.
  • Created a new Node.js project with npm init.
  • Set up a basic Express server.
  • Created a route to serve user data as JSON.
  • Tested the API using Postman.
See also  Day 8: Storing Data Securely and Implementing File Uploads

This forms the foundation of your RESTful API. In the next lesson, we’ll dive deeper into routing, middleware, and organizing your project structure.


Next Up: Day 2 – Creating Routes and Controllers

In Day 2, we will focus on organizing your API by creating different routes and controllers. You’ll learn how to structure your code to handle different resources, making it easier to manage as your API grows.

Stay tuned for more advanced features tomorrow!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.