Styling html pages in Node.js


In html files we can simply add style in head section −

<html>
   <head>
      <style>
         //add css code
      </style>
   </head>
<body>
</body>
</html>

We can add inline css styles as well in html directly.

Generally css is separated from the html code. Third option add css is to include a css file .

How to serve static files in Node.js?

Generally css files are added with below tag −

<head>
   <link rel=”stylesheet” href=”path-to-css-file”>
</head>

Express js provides a middleware to seve static file. This middleware gives read access to given folder.

app.use(express.static(path.join(__dirname, ‘public’)));

path: its our core module in node.js

__dirname: Actual path to root folder of project

Public: Folder name which has read access fom node server

Css files will be stored in public folder.

Example usage of css file −

App.js

const http = require('http');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false})); app.use(express.static(path.join(__dirname, 'public')));
app.use('/test',route);
app.use((req, res,next)=>{
   res.status(404).send('<h1> Page not found </h1>');
});
const server = http.createServer(app);
server.listen(3000);

create a public folder in main project folder and store a main.css file under css folder in it.

Main.css

input {
   width:200px;
   height:20px;
}

route.js

const path = require('path');
const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
   // res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username">    <button type="submit"> Send </button> </form>');
   res.sendFile(path.join(__dirname, 'views', 'add-user.html'));
});
router.post('/post-username', (req, res, next)=>{
   console.log('data: ', req.body.username);
   res.send('<h1>'+req.body.username+'</h1>');
});
module.exports = router;

add-user.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <link rel="stylesheet" href="/css/main.css">
   </head>
<body>
   <form action="/test/post-username" method="POST"> <input type="text" name="username"> <button          type="submit"> Send </button> </form>
</body>
</html>

Run : npm start

Browse: localhost:3000/test/add-username and we will updated css for input field from css file.

Updated on: 13-May-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements