Express JS express.json() Function - GeeksforGeeks (2024)

Last Updated : 12 Aug, 2024

Summarize

Comments

Improve

The express.json() function is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.It’s a critical component for handling JSON data in RESTful APIs and web applications, allowing the server to automatically parse JSON data from the request body.

Syntax:

express.json( [options] )

Parameters:

  • The options parameter has various properties like inflate, limit, type, etc.

Return Value: It returns an Object.

Features

  • Automatic Parsing: Automatically parses JSON data in the request body and makes it available on req.body.
  • Error Handling: If the JSON is malformed, express.json() throws a 400 Bad Request error, preventing the request from proceeding.
  • Lightweight: Built directly into Express, eliminating the need for additional packages to handle JSON parsing.
  • Integration with Other Middleware: Can be used in conjunction with other middleware like express.urlencoded() for handling different content types.

Steps to Install the Express Module

Step 1: You can install this package by using this command.

npm install express

Step 2: After installing the express module, you can check your express version in the command prompt using the command.

npm version express

Step 3: After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.

node index.js

Project Structure:

Express JS express.json() Function - GeeksforGeeks (1)

Project Structure

Example 1: Below is the code example of the express.json().

JavaScript
// Filename - index.jsconst express = require('express');const app = express();const PORT = 3000;app.use(express.json());app.post('/', function (req, res) { console.log(req.body.name) res.end();})app.listen(PORT, function (err) { if (err) console.log(err); console.log("Server listening on PORT", PORT);}); 

Step to run the program: Run the index.js file using the below command

node index.js

Output: Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/json’ and body {“name”:”GeeksforGeeks”}, then you will see the following output on your console:

Server listening on PORT 3000GeeksforGeeks

Example 2: Below is the code example of the express.json().

JavaScript
// Filename - index.jsconst express = require('express');const app = express();const PORT = 3000;// Without this middleware // app.use(express.json()); app.post('/', function (req, res) { console.log(req.body.name) res.end();})app.listen(PORT, function (err) { if (err) console.log(err); console.log("Server listening on PORT", PORT);});

Steps to run the program: Run the index.js file using the below command:

node index.js

Output: Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/json’ and body {“name”:”GeeksforGeeks”}, then you will see the following output on your console:

Server listening on PORT 3000TypeError: Cannot read property 'name' of undefined

Summary

The express.json() middleware is an essential part of any Express.js application dealing with JSON data. It simplifies the process of handling JSON payloads, ensuring that the data is automatically parsed and available for use in your routes. By integrating express.json() into your application, you can streamline the handling of JSON requests and enhance the robustness of your API or web application.



Please Login to comment...

Express JS express.json() Function - GeeksforGeeks (2024)
Top Articles
Deworming drugs for soil-transmitted intestinal worms in children: effects on nutritional indicators, haemoglobin, and school performance
How to back up your iPhone on a Mac
3 Tick Granite Osrs
Calvert Er Wait Time
jazmen00 x & jazmen00 mega| Discover
Craigslist Pets Longview Tx
Restored Republic January 20 2023
South Carolina defeats Caitlin Clark and Iowa to win national championship and complete perfect season
Gameplay Clarkston
Cinepacks.store
United Dual Complete Providers
Nestle Paystub
Find your energy supplier
Cincinnati Bearcats roll to 66-13 win over Eastern Kentucky in season-opener
Goldsboro Daily News Obituaries
Synq3 Reviews
Walthampatch
Munich residents spend the most online for food
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
Aris Rachevsky Harvard
Cbssports Rankings
Unionjobsclearinghouse
Melendez Imports Menu
Scream Queens Parents Guide
LCS Saturday: Both Phillies and Astros one game from World Series
Home
Drying Cloths At A Hammam Crossword Clue
Bay Area Craigslist Cars For Sale By Owner
Workshops - Canadian Dam Association (CDA-ACB)
§ 855 BGB - Besitzdiener - Gesetze
Nk 1399
John Philip Sousa Foundation
Past Weather by Zip Code - Data Table
Barbie Showtimes Near Lucas Cinemas Albertville
Isablove
Bursar.okstate.edu
+18886727547
Warn Notice Va
Metro By T Mobile Sign In
The Legacy 3: The Tree of Might – Walkthrough
Does Iherb Accept Ebt
Samsung 9C8
Louisville Volleyball Team Leaks
Midsouthshooters Supply
Tokyo Spa Memphis Reviews
Royals Yankees Score
Citymd West 146Th Urgent Care - Nyc Photos
Greg Steube Height
Jackerman Mothers Warmth Part 3
Joy Taylor Nip Slip
Congressional hopeful Aisha Mills sees district as an economical model
Aspen.sprout Forum
Latest Posts
Article information

Author: Delena Feil

Last Updated:

Views: 5944

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.