Express - Serving Static File CSS
In this tutorial we see how to styling a express application with CSS.
Set Up Static File Directory
Create a directory as public to store the css files.
mkdir public cd public mkdir css
Inside the css folder create style.css file.
Add the CSS styles in public/css/style.css
body { background-color: #4c9fe4; } p { color: #fffcfc; font-size: 25px; }
Serve the public Directory in Express
Express to serve the public directory so that it can serve the CSS and other static assets.
const express = require('express'); const path = require('path'); const hbs = require('hbs'); const app = express(); // Serve static files from the public directory app.use(express.static(path.join(__dirname, 'public'))); // Set up handlebars as the view engine app.set('view engine', 'hbs'); // Define the location for your views app.set('views', path.join(__dirname, '/views')); // Define a route to render a template app.get('/', (req, res) => { res.render('index'); }); const PORT = 5000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Handlebars with External CSS Link
views/index.hbs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/css/style.css"> </head> <body> <p>Welcome to the world.</p> </body> </html>
Run the Server
Run the server use the command is given below.
node index.js
D:\express-app>node index.js Server is running on http://localhost:5000