![]() |
VOOZH | about |
In Node.js, a query string is the part of a URL used to send small key-value data to the server, mainly with GET requests for filtering and fetching information without using a request body.
Example URL:
http://localhost:8080?id=1&name=NicolNode.js provides two main ways to work with query strings:
The querystring module provides utilities to parse and stringify query strings.
Importing Module: You can include the module using the following code:
const querystring = require('querystring');Note: The querystring module is built-in in Node.js and does not require installation.
Example 1: Parsing a Query String (parse())
Output:
This is parsed Query String : { user: 'GEEKSFORGEEKS', year: '2021' }If the server is running and you open the following URL in the browser:
http://localhost:3000?id=2Output:
{
"user": {
"id": 2,
"name": "James"
}
}
Example 2: Converting Object to Query String (stringify())
Output:
name=Testing&company=GeeksforGeeks&content=Article&date=9thMarch2021URL and URLSearchParams are modern, built-in APIs in Node.js used to easily parse, read, and manage query parameters from URLs with clean and standardized syntax.
Example:
Assumed Request URL:
http://localhost:8080?id=1&name=NicolOutput:
1
NicolQuery parameters allow a GET request to retrieve specific data from the server using values passed in the URL, without sending a request body.
Query strings provide a simple and efficient way to send small amounts of data to the server through the URL without using a request body.