Query parameters
- Node.js course
- Intermediate
- Lesson 37/116
- 5 min
Learn query parameters with req.query.
Query parameters
The part of a URL after ? carries query parameters. Example: /search?q=book. Express parses these into the req.query object. req.query.q gives "book".
Query parameters differ from route parameters: a route parameter is part of the path (:id), a query parameter is appended to the URL (?key=value). Multiple query parameters are separated by &: /search?q=book&s=new. Here req.query.q and req.query.s are each available. Query parameters are used for filtering, sorting and search options.
Multiple query parameters
Multiple query parameters in a URL are separated by &. Example: /products?category=electronics&sort=price. Express puts each in req.query: req.query.category and req.query.sort.
Query parameters are optional; if not in the URL they are not in req.query either. So it is good practice to check whether a parameter exists: if (req.query.sort) { ... }. Route parameters, by contrast, are always present (if the route matched). This difference matters: :id is required, ?q= is optional. In API design, required identifiers go as route parameters, optional filters as query parameters.
Practice Write a search query route
Define the route app.get("/search", (req, res) => { res.send("Search: " + req.query.q); }). The server requests /search?q=book.
Starter code
const express = require("express");
const app = express();
// Define a /search route
// Read the query parameter and respond
// write here
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/search?q=kitap", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Sample solution
const express = require("express");
const app = express();
app.get("/search", (req, res) => {
res.send("Search: " + req.query.q);
});
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/search?q=kitap", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Expected output
Yanıt: Arama: kitap
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the query access
app.get("/search", (req, res) => {
res.send("Arama: " + req.____.q);
});
app.get("/search", (req, res) => {
res.send("Arama: " + req.query.q);
});
Explanation: req.query.q reads the query parameter.
2 Match each piece to its role
| Term | Meaning |
|---|---|
req.query |
Query parameters |
req.params |
Route parameters |
?q=book |
URL query string |
& |
Parameter separator |
3 What does req.query return?
/search?q=kitap&s=yeni- Parametre nesnesi Correct answer
- Bir dizi
- Bir dize
- A number
Explanation: req.query returns an object.