Static Files
Part of the Express Basics section of Coddy's Node.js journey. Lesson 9 of 20.
A stylesheet or an image never changes, and a route for each file would be busywork.
app.use(express.static('assets'));express.static('assets') serves the files of the assets folder at their own names: assets/logo.png answers GET /logo.png. The folder name is not part of the URL. Express picks the content type from the extension: text/css for .css, image/png for .png. A path with no file goes on to your routes.
app.use adds a function that runs for every request; the next chapter is about those. Your project now has a public folder with a stylesheet.
Challenge
Easy- Serve the
publicfolder, soGET /style.cssanswers the file. - Link it from the home page with
<link rel="stylesheet" href="/style.css">.
Open / in the page view, then send GET /style.css and GET /missing.css.
Try it yourself
import express from 'express';
import { recipes } from './data.js';
const app = express();
const escapeHtml = (text) =>
text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
app.get('/', (req, res) => {
const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
res.send(`<h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});
// 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');
});