Query Strings
Part of the Express Basics section of Coddy's Node.js journey. Lesson 5 of 20.
A list page often needs options, like which recipes to show, and a new route for each option would be too many.
app.get('/books', (req, res) => {
const { author } = req.query;
res.send(author ? 'Books by ' + author : 'All books');
});The query string is the part of the URL after ?, and Express puts it in req.query. GET /books?author=Austen gives req.query.author === 'Austen'. With no ? it is undefined. Several options join with &: /books?author=Austen&year=1813.
A route parameter is part of the path and names one thing. A query option filters or sorts a list, and can be left out.
Challenge
EasyGET /recipes?tag=veganlists only the titles of recipes with that tag, one per line.- Without
tag, it lists every title.
Send GET /recipes?tag=vegan, GET /recipes?tag=dessert and GET /recipes.
Try it yourself
import express from 'express';
import { recipes } from './data.js';
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Recipe Box');
});
// type('text') sends plain text, so each title shows on its own line.
app.get('/recipes', (req, res) => {
res.type('text').send(recipes.map((recipe) => recipe.title).join('\n'));
});
app.get('/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).send('No such recipe');
return;
}
res.send(recipe.title);
});
app.get('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});