Page Content

Tutorials

What is the HTTP Methods in Node.js? Methods in Express.js

Core HTTP Methods in Node.js

Based on a request/response paradigm, HTTP (Hypertext Transfer Protocol) is a stateless data transfer protocol. This implies that each request or answer that clients send to servers does not retain any information about past exchanges. This type of quick network connection pattern is what Node.js is made for.

The kind of action a client wishes to do on a server specified via HTTP methods, sometimes referred to as verbs. These four are among the most prevalent ones:

Core HTTP Methods in Node.js
  1. GET:
    • Purpose: The GET technique is employed to retrieve information from the server. When you click a link or enter a URL into the address bar of a browser, this is the most common way.
    • Use Cases: For instance, you could use GET to receive a list of anime from a server, retrieve all users, or retrieve a particular user by their ID.
    • Statelessness: GET requests usually don’t have a request body and should be idempotent, which means that sending the same request more than once will cause the server to react in the same way.
  2. POST:
    • Purpose: Data from forms or other objects can be sent to the server using the POST method. Data submission to a designated for processing is its main function, which frequently leads to the new development.
    • Use Cases: Adding a new item to a list, generating a new user, or sending application data to a server.
    • Non-Idempotent: POST requests, in contrast to GET requests, are typically not idempotent. This means that sending the same POST request more than once may result in the creation of several or impact the server’s state in different ways. Care should be used while using this method because it frequently has a significant impact on the status of an application.
  3. PUT:
    • Purpose: When updating a server, the PUT technique is utilised. With the parameters supplied in the request body, it is meant to generate or replace a given URL.
    • Use Cases: Use cases include editing an existing item in a data database or correcting misspelt anime names. PUT requests, like GET requests, are typically idempotent.
  4. Delete:
    • Purpose: The purpose of the DELETE method is to delete an item from the server. In order to request the removal, it is called against a URL.
    • Use Cases: Eliminating a user based on their ID or deleting an anime from a list. DELETE requests, like PUT requests, are typically idempotent.

The development of REST APIs (Representational State Transfer Application Programming Interfaces), which use HTTP to transmit data across computers, is based on these HTTP methods.

Implementing Methods in Express.js

Express.js is a simple and adaptable framework for Node.js web applications. It streamlines the development of HTTP APIs and web applications. Prior to Express, Node.js’s native http module could be used to write lengthy, unreadable code to handle server logic and routing. “Pretty easy” is how Express puts it.

You usually need to install Express using npm in order to get started: npm install express --save.

Requiring the express module, establishing an app instance, specifying a port to listen on, and configuring route handlers are all necessary for a simple Express application.

Setting up a basic Express Server

Installing a simple Express server Create a file first, such as app.js, and add the following:

// Import the top-level function of express
const express = require('express');

// Creates an Express application using the top-level function
const app = express();

// Define port number, e.g., 3000
const port = 3000; 

// Make the app listen on the defined port
app.listen(port, function() {
  console.log('Server listening on http://localhost:' + port); 
});

To run this, save it as app.js and execute node app.js in your terminal. You’ll see “Server listening on http://localhost:3000” in your console.

Implementing GET Requests in Express

When handling HTTP GET requests in Express, you utilise the app.get() method. Two primary arguments are required for this method to function: the path (URL) and a callback function to execute upon path visitation.

In most cases, the callback function is given two objects:

  • request (req): Provides information about the HTTP request, including the URL, headers, and any query parameters.
  • response (res): This parameter is used to indicate how the server should react to the request, including how to establish HTTP status codes and transfer data.

Let’s modify app.js to include a GET request for a “Hello World” message and a list of users:

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

// Example GET route for the homepage
app.get('/', (req, res) => { 
  // Provide a text response
  res.send('Hello, World!'); 
});

// Example GET route for fetching a list of users
app.get('/api/users', function(req, res){ 
  const users = [ 
    { id: 1, name: "John Doe", email: "john@example.com" },
    { id: 2, name: "Jane Smith", email: "jane@example.com" }
  ];
  // Return response as JSON
  res.json(users); 
});

// Example GET route using route parameters for a specific user profile
app.get('/api/users/:id', function(req, res){ 
  const userId = req.params.id; // Access the 'id' parameter from the URL 
  const users = [
    { id: 1, name: "John Doe", email: "john@example.com" },
    { id: 2, name: "Jane Smith", email: "jane@example.com" }
  ];
  const user = users.find(u => u.id == userId);
  if (user) {
    res.json(user);
  } else {
    res.status(404).send('User not found'); // Set status code and send message
  }
});

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

Expected Output (console after running node app.js):

Server listening on http://localhost:3000

Expected Output (browser/cURL for http://localhost:3000):

Hello, World!

Expected Output (browser/cURL for http://localhost:3000/api/users):

[
  { "id": 1, "name": "John Doe", "email": "john@example.com" },
  { "id": 2, "name": "Jane Smith", "email": "jane@example.com" }
]

Expected Output (browser/cURL for http://localhost:3000/api/users/1):

{ "id": 1, "name": "John Doe", "email": "john@example.com" }

Expected Output (browser/cURL for http://localhost:3000/api/users/99):

User not found

Implementing POST Requests in Express

In Express, the app.post() method is used to process POST requests. Parsing the request body using middleware is an essential step for POST requests (and PUT/DELETE requests as well). Express.json() and express.urlencoded() can be used straight from Express, alternatively the body-parser module is frequently used for this. The req.body object contains the body-parser thanks to this middleware.

Let’s extend app.js to handle POST requests for creating a new user:

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

// Middleware to parse JSON request bodies
app.use(express.json()); 
// If you also expect URL-encoded form data
app.use(express.urlencoded({ extended: true })); 

let users = [ // Now a mutable array to demonstrate POST
  { id: 1, name: "John Doe", email: "john@example.com" },
  { id: 2, name: "Jane Smith", email: "jane@example.com" }
];

// Existing GET routes...

// Example POST route for creating a new user
app.post('/api/users', (req, res) => { 
  const newUser = req.body; // Access the request body 
  // Assign a simple ID (in a real app, this would be from a database)
  newUser.id = users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1;
  users.push(newUser); [13, 57]
  res.status(201).json(newUser); // Respond with the created user and 201 Created status
});

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

Expected Output (console after running node app.js):

Server listening on http://localhost:3000

Expected Output (cURL for a POST request to http://localhost:3000/api/users with body {"name": "Alice", "email": "alice@example.com"}):

{"name":"Alice","email":"alice@example.com","id":3}

If you then make a GET request to http://localhost:3000/api/users, you’d see Alice added to the list:

[
  { "id": 1, "name": "John Doe", "email": "john@example.com" },
  { "id": 2, "name": "Jane Smith", "email": "jane@example.com" },
  { "id": 3, "name": "Alice", "email": "alice@example.com" }
]

Implementing PUT and DELETE Requests in Express (Briefly)

PUT and DELETE requests in Express follow a similar pattern to POST requests. They also use the respective app.put() and app.delete() methods. Like POST, they often involve accessing URL parameters (req.params) to identify the resource and may use the request body (req.body) for update data (PUT) or simply for confirmation (DELETE).

Set Up the Project Directory

Open your terminal or command prompt:

bashCopyEditmkdir user-api
cd user-api

Initialize Node.js Project

bashCopyEditnpm init -y

This creates a package.json file.

Install Express

bashCopyEditnpm install express

Create the Server File

Create a file named index.js (or server.js) and copy-paste this corrected and complete version of your code:

index.js (updated with fixes and sample data)

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

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Sample user data
let users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
];

// PUT route: update or create user
app.put('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const updatedUser = req.body;
const index = users.findIndex(u => u.id === userId);

if (index !== -1) {
users[index] = { ...users[index], ...updatedUser, id: userId };
res.json(users[index]);
} else {
const newUser = { ...updatedUser, id: userId }; // FIX: define newUser properly
users.push(newUser);
res.status(201).json(newUser);
}
});

// DELETE route: remove user
app.delete('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const initialLength = users.length;
users = users.filter(u => u.id !== userId);

if (users.length < initialLength) {
res.status(204).send(); // No Content
} else {
res.status(404).send('User not found');
}
});

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

Building reliable web apps and APIs in Node.js is easy if you know how to use Express.js to create these fundamental HTTP techniques.

Index