DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Memory Management in Couchbase’s Query Service
  • How to Build Slack App for Audit Requests
  • Idempotency in Distributed Systems: When and Why It Matters
  • Perfecting CRUD Functionality in NextJS

Trending

  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • Debugging Core Dump Files on Linux - A Detailed Guide
  • Why Documentation Matters More Than You Think
  • Segmentation Violation and How Rust Helps Overcome It
  1. DZone
  2. Coding
  3. JavaScript
  4. Express Tutorial: HTTP Requests in Express.js

Express Tutorial: HTTP Requests in Express.js

Master requests and routing with Express.js

By 
Arslan ud Din Shafiq user avatar
Arslan ud Din Shafiq
·
Sep. 09, 19 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
30.9K Views

Join the DZone community and get the full member experience.

Join For Free

old-rusted-train-moving-along-tracks

All aboard!

Requests and Routing

HTTP requests are binary information packets that a computer or client sends to another computer or server to communicate.

Routing is basically defined as the process of selecting a path for traffic or request in a network or in a web framework. In Express, we can access web pages, files, images, scripts, stylesheets, etc. at different paths set by route. To define a route in Express, we use app.method (path, handler).

You may also like: Full-Stack Vue App With Node, Express, and MongoDB.

App.method (Path, Handler)

This is a function that is used to define various routes for different types of requests. Path is address of route and handler is the function that will receive the request and give a response to that request.

HTTP Requests Methods in Express JS

Types of Request Methods for Routes (app.method(path, handler))

GET It is used when data fetching is required from the server for representation on the client-side.  
POST  It is used when the request is sent through forms secretly. The server accepts data in the request as a new entity identified by URI.  
PUT  It is used to store and update data. If an object exists already, it updates or modifies it. If the object does not exist, it creates new one.
DELETE  It is used to delete data from the server.

GET and POST Requests in Express JS

Let’s take an example of a /home route. In this example, we have defined a route at  http://localhost:3000/home. The server receives a get type request when we access this address. After receiving the request, a callback function defined in app.method gets executed, which sends the string  “Welcome to Homepage” as a response to the client

After accessing  http://localhost:3000/home, you will see the following response on the browser.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//creates get function with request and response parameters
app.get('/home', function(req, res){

    //sends response to client or browser
    res.send("Welcome to Homepage");

});
//listens to server at port 3000
app.listen(3000);


http requests
http requests

Now, just try to access different routes without defining. For example, we haven’t defined any route in the above code for path  /login. You will see Cannot GET / Login response on requesting this address.

http requests error on request express js
HTTP requests error on request Express.js

Now to check the POST request method, we will need to use cURL or any app for sending a POST request. I will use Insomnia REST Client for sending and receiving requests and responses respectively. It allows you to select an HTTP request type, set path on which the request has to be sent, and shows a response.

http requests post request in express js
HTTP requests post request in Express.js

GET and POST Requests in Express JS

Let’s take another example by defining GET and POST request at the same route.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//creates get function with request and response parameters
app.get('/home', function(req, res){

    //sends response to client or browser
    res.send("Welcome to GET");

});
//creates post function with request and response parameters
app.post('/home', function(req, res){

    //sends response to client or browser
    res.send("Welcome to POST");

});

//listens to server at port 3000
app.listen(3000);


GET Request Output in Express JS

When you will access /home route with GET request, you will see Welcome to GET response.

http requests get request express js
HTTP requests get request Express.js

POST Request Output in Express JS

But, when you access /home route with a POST request, you will see Welcome to POST response.

http requests express js post request
HTTP requests Express.js post request

PUT and DELETE Requests in Express JS

Similarly, modify the code to check PUT and DELETE request.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//creates get function with request and response parameters
app.delete('/home', function(req, res){

    //sends response to client or browser
    res.send("Welcome to DELETE");

});
//creates post function with request and response parameters
app.put('/home', function(req, res){

    //sends response to client or browser
res.send("Welcome to PUT");

});

//listens to server at port 3000
app.listen(3000);


You will see Welcome to PUT response for your PUT method route and Welcome to DELETE response for your DELETE method route.

Outputs for PUT and DELETE Requests

http requests output for PUT Request in Express js
HTTP requests output for PUT Request in Express.js


http requests DELETE Request in Express JS
HTTP requests DELETE Request in Express.js

All Requests Route in Express.js

In some scenarios, we have to use all the methods for a single route. For example, in middleware, we use this. Look at the code below, it has a route with all method. It will respond to all HTTP requests. The response will be the same for all HTTP requests no matter if it is GET, POST, DELETE or PUT.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//creates all function with request and response parameters
app.all('/home', function(req, res){

    //sends response to client or browser
    res.send("Welcome to Home");

});

//listens to server at port 3000
app.listen(3000);


In the next tutorial, you will learn how to add static and dynamic routing in Express JS.


Related Articles

  • Web Development Comparison: Spring Boot vs. Express.js.
  • 10 Powerful Node.js Frameworks to Accelerate Web Development.    

Express Requests

Opinions expressed by DZone contributors are their own.

Related

  • Memory Management in Couchbase’s Query Service
  • How to Build Slack App for Audit Requests
  • Idempotency in Distributed Systems: When and Why It Matters
  • Perfecting CRUD Functionality in NextJS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!