Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Reading Path Parameters in Node.js
Next article icon

Reading Path Parameters in Node.js

Last Updated : 14 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Path parameters are an essential part of RESTful APIs, allowing the server to capture values from the URL and use them in request handling. This capability is crucial for creating dynamic and flexible endpoints. In Node.js, especially when using frameworks like Express.js, handling path parameters is straightforward and efficient. In this article, we'll explore how to read path parameters in Node.js and use them in your applications.

Understanding Path Parameters

Path parameters are segments of a URL that are defined in the path of an endpoint and are used to pass data to the server. They are commonly used for resource identification and can be essential for routing purposes.

For example, in the URL http://example.com/users/123, 123 is a path parameter that might represent a user ID.

Setting Up a Node.js Environment

Before we dive into reading path parameters, let's set up a basic Node.js environment.

Step 1: Install Node.js and npm

Ensure you have Node.js and npm installed. You can download them from the official Node.js website.

Step 2: Initialize a New Project

Create a new directory for your project and initialize it with npm

mkdir myapp
cd myapp
npm init -y

Step 3: Install Express

Express is a popular web framework for Node.js that simplifies routing and handling HTTP requests. Install it using npm

npm i express

Step 4: Create a Server File

Create a new file named server.js

touch server.js

Project Structure:

Screenshot-2024-06-13-152451

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.19.2"
}

Example: Implementation to write the code for reading Path Parameters in Node.js.

javascript
// server.js  const express = require("express")  const path = require('path')  const app = express()   const PORT = process.env.port || 3000   // View Engine Setup  app.set("views", path.join(__dirname))  app.set("view engine", "ejs")   app.get("/user/:id/:start/:end", function(req, res){    const user_id = req.params['id']   const start = req.params['start']   const end = req.params['end']     console.log("User ID :",user_id);  console.log("Start :",start);  console.log("End :",end); })   app.listen(PORT, function(error){   if (error) throw error   console.log("Server created Successfully on PORT", PORT)  })  

Step to Run Application: Run the application using the following command from the root directory of the project

node server.js

Output: Your project will be shown in the URL http://localhost:3000/

Open browser and type this URL "http://localhost:3000/user/1234/1/10" as shown belowBroswer URL

Go back to console and you can see the path parameter value as shown below: Output of above command

So this is how you can use the path parameter in Node.js which offers a unique opportunity for the user to control the representations of resources.


Next Article
Reading Path Parameters in Node.js

G

gouravhammad
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Node.js
  • NodeJS-Questions

Similar Reads

    Reading Query Parameters in Node
    In Node.js, query parameters are typically accessed from the URL of a GET request. When using the core HTTP module or a framework like Express, query parameters can be parsed and accessed for dynamic functionality.A query string refers to the portion of a URL (Uniform Resource Locator) that comes af
    2 min read
    Node.js querystring.parse() Method
    The querystring.parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding forma
    3 min read
    Node.js process.stdin Property
    The process.stdin property is an inbuilt application programming interface of the process module which listens for the user input. The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event. Syntax: process.stdin.on();Return Value: It doesn't return
    2 min read
    Node.js path.parse() Method
    The path.parse() method is used to return an object whose properties represent the given path. This method returns the following properties: root (root name) dir (directory name) base (filename with extension) ext (only extension) name (only filename) The values of these properties may be different
    2 min read
    How to Parse JSON using Node.js?
    JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configu
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences