How to handle URL parameters in Express ?
Last Updated :
31 Jul, 2024
In this article, we will discuss how to handle URL parameters in Express. URL parameters are a way to send any data embedded within the URL sent to the server. In general, it is done in two different ways.
Steps to Create Express Application:
Let's implement the URL parameter in an Express Application and see it in action.
Step 1: Create an Express Application with the below commands.
npm init -y
Step 2: Install Express library with npm and add it to dependency list
npm install --save express
Example: Adding server.js
- In the project directory, create a file named index.js.
- Create an express server in the file and listen for connections.
JavaScript
// server.js
// create an express object
const app = require("express")();
// server port
const PORT = 8080;
// listen for connections
app.listen(PORT, () => {
console.log(`server is listening at port:${PORT}`);
});
- In the above code, an express app is created by importing the express library.
- Server is listening in the 8080 Port for any incoming request, on successful start server will print a log in the console.
Approach 1: Using queries
In this method, the URL parameter will be send in the URL as queries. Queries are appended at the end of actual url with a question character "?" appended at the last. Every query value will be mapped as key - value pairs and will be delimited with an ampersand "&" symbol.
http://example.com/api/?id=101&name=ragul
In the above example the queries are passed like below key - value pairs
Example: Using queries:
- To use URL parameters in type of queries, use the "req.query" property from request object in Express.
- Express will automatically add the queries from URL in the req.query as a Javascript Object.
JavaScript
// server.js
// create an express object
const app = require("express")();
// server port
const PORT = 8080;
// using queries
app.get("/api", (req, res) => {
// get the URL parameters passed by
// query with req.query
const queries = req.query;
res.send(queries);
});
// listen for connections
app.listen(PORT, () => {
console.log(`server is listening at port:${PORT}`);
});
- queries are being read from req.query and just simply returned as response.
Output:
Approach 2: Using Route parameter
In route parameters, instead of sending as queries, embed the value inside the actual URL itself.
For example
http://example.com/api/:id/:name
Here, userid and username are placeholder for route parameter. To use the above URL parameter send the request like below.
http://example.com/api/101/ragul
- :userid is mapped to 101
- :username is mapped to ragul
Example: Using route params
- To use the route parameter, define the parameters in the URL of the request.
- Every parameter should be preceded by a colon ":"
- Access the route parameters from the request object's params property, it will return a Javascript Object.
JavaScript
// server.js
// create an express object
const app = require("express")();
// server port
const PORT = 8080;
// Using params
app.get("/api/:id/:name", (req, res) => {
// get the URL parameter from URL
// with req.params
const params = req.params;
res.send(params);
});
// listen for connections
app.listen(PORT, () => {
console.log(`server is listening at port:${PORT}`);
});
The above code will map the id to the immediate value next to "/api/" and for the name it will add the second next value in the URL parameter.
Output:
Similar Reads
How To Handle Route Parameters in Express? Route parameters in ExpressJS capture dynamic values from URLs, like /users/:userId. These values are accessible in your route handler via req.params, enabling dynamic content generation. This allows for creating reusable routes that handle various inputs with a single pattern.JavaScriptapp.get('/us
4 min read
How to use get parameter in Express.js ? 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, UP
2 min read
How to Use Handle Get Request in Express.js ? Express.js is a popular web application framework for Node.js, known for its simplicity and flexibility. One of the fundamental tasks in web development is handling HTTP requests, and GET requests are among the most common. This article will guide you through the process of handling GET requests in
2 min read
How to handle redirects in Express JS? Express JS uses redirects to send users from one URL to another. This can be done for various reasons, such as handling outdated URLs or guiding users through a process. In ExpressJS, you define routes and use them to direct users to the desired URL. It's a way to keep your application organized and
2 min read
How to handle sessions in Express ? ExpressJS is a small framework that works on top of Node web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. It adds helpful utilities to Node HTTP objects and facilitates the render
4 min read