Static Files
Part of the Express Basics section of Coddy's Node.js journey. Lesson 11 of 23.
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
EasyRecipe Box gets a stylesheet. The file is ready in the public folder; your server only has to hand it out.
- In
server.js, right afterconst app = express();, serve every file in thepublicfolder withexpress.static. Thenpublic/style.cssis served at/style.css. - Make the home page load it: put
<link rel="stylesheet" href="/style.css">at the start of the HTML that the/route sends.
Try it: Press Run and send /. The page now uses the stylesheet. Send /style.css: status 200, the CSS text, and a Content-Type of text/css in the Headers tab. Send /missing.css: there is no such file, so the request goes on to your routes. None matches, and Express responds with 404.
Try it yourself
import {escapeHtml} from './html.js';
import express from 'express';
import { recipes } from './data.js';
const app = express();
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');
});
All lessons in Express Basics
Practice on your own: Express playground