A minimal Express app demonstrating query strings with req.query.
Query strings are the “options panel” for a route:
- they don’t change the route path
- they modify the request using key/value pairs after
?
Example:
/search?keyword=turbo&sort=desc- Node.js
- npm
Check:
node -v
npm -vnpm installnpm startOpen:
http://localhost:3000/search?keyword=turbo&sort=desc
You’ll get:
Searching for turbo sorted by descOpen:
http://localhost:3000/search?keyword=turbo
You’ll get:
Searching for turbo sorted by undefined(That’s intentional — it shows sort is optional unless you enforce it.)
Open:
http://localhost:3000/search
You’ll get:
Please specify a keyword.npm run watchEdit app.js, save, refresh.
Stop with:
Ctrl + C
Query string values land here:
req.querySo:
/search?keyword=turbo&sort=descreq.query = { keyword: "turbo", sort: "desc" }
.
├── app.js
├── package.json
└── README.mdNode2Know-LEARN-1.0