HTML Pages
Part of the Express Basics section of Coddy's Node.js journey. Lesson 8 of 20.
Your recipes belong on a real page, and a browser only draws HTML. A page is a string of HTML: res.send sends it as text/html, and a template string fills it with data.
app.get('/weather/:city', (req, res) => {
const city = escapeHtml(req.params.city);
res.send(`<h1>Weather in ${city}</h1><p>Sunny</p>`);
});Text from outside, like a URL part or a title someone typed, may hold < or &. Put into HTML as it is, <script> becomes code that runs in your visitor's browser. escapeHtml turns those characters into entities the browser shows as text. It replaces & first, so the & of < is not replaced again.
const escapeHtml = (text) =>
text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');Challenge
EasyGET /answers an HTML page listing every recipe title.- Each title links to its page, like
<a href="/recipes/2">. - Every title goes through
escapeHtml.
Open / in the page view and click Fish & Chips.
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) => {
const { tag } = req.query;
const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
res.type('text').send(list.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('/api/recipes', (req, res) => {
res.json(recipes);
});
app.get('/api/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
res.json(recipe);
});
app.get('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
This lesson includes a short quiz. Start the lesson to answer it and track your progress.