Passing multiple parameters in a URL is an essential task in web development. In Node.js, it is a straightforward and effortless process. In this tutorial, we will learn how to pass multiple parameters in URL in Node.js step by step.
Step 1: Requirement
First, we need to have Node.js installed on our system. If you haven’t installed Node.js yet, click on this link to install Node.js.
Step 2: Initialize Node.js Project
Create a new folder and initialize it as a Node.js project using the npm init command in the terminal.
1 2 3 |
mkdir projectName cd projectName npm init |
Fill in all the required information and run the command. It will create a package.json file in the root directory.
Step 3: Install Express.js
Next, we need to install the Express.js framework, which is a popular framework for Node.js. Run the following command in the terminal to install Express.js.
1 |
npm install express --save |
Step 4: Create Node.js File
Create a new file named index.js in the root folder of your Node.js project.
1 |
touch index.js |
Write the following code in index.js to use the Express.js framework.
1 2 |
const express = require('express') const app = express() |
Step 5: Create a Route
Create a new route in the Node.js file. In this example, we will create a route that accepts two parameters, a name, and age, in the URL.
1 2 3 4 5 |
app.get('/user/:name/:age', function (req, res) { const name = req.params.name const age = req.params.age res.send(`Hello ${name}, Your age is ${age}`) }) |
Step 6: Test the Application
Now, we can test our application using a web browser or Postman. Open your web browser and enter the following URL:
http://localhost:3000/user/John/25
You should see the following output:
Hello John, Your age is 25
Congratulations, you have successfully passed multiple parameters in the URL using Node.js.
In conclusion, passing multiple parameters in the URL in Node.js is a simple process. We just need to create a route that accepts parameters and use them in our application. We can use this technique in many web applications to pass multiple user inputs.