Open In App

How to use get parameter in Express.js ?

Last Updated : 10 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UPDATE, etc). 

We can create an API endpoint receiving a GET request with the help of app.get() method. 

Syntax: 

app.get(route, (req, res) => {
    // Code logic
});

Route parameters are the name URL segments that capture the value provided at their position. We can access these route parameters on our req.params object using the syntax shown below.

app.get(/:id, (req, res) => {
    const id = req.params.id;
});

 

Project Setup:

Step 1: Install Node.js if you haven’t already.

Step 2: Create a folder for your project and cd (change directory) into it. Create a new file named app.js inside that folder. Now, initialize a new Node.js project with default configurations using the following command.

npm init -y

Step 3: Now install express inside your project using the following command on the command line.

npm install express

Project Structure: After following the steps your project structure will look like the following.

app.js




const express = require('express');
const app = express();
  
app.get('/', (req, res) => {
  res.send('<h1>Home page</h1>');
});
  
app.get('/:id', (req, res) => {
  res.send(`<h1>${req.params.id}</h1>`);
});
  
app.listen(3000, () => {
  console.log('Server is up on port 3000');
});


Step to run the application: You can run your express server by using the following command on the command line.

node app.js

Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/some_id and you will view the following output.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads