Serving html pages from node.js

Node.jsServer Side ProgrammingProgramming

So far we sent html code directly from the send(0 function in response object. For sending larger code, we definitely require to have a separate file for html code.

sendFile() function

Response object gives a sendFile() function to return a html file to client.

How to provide path to html file in sendFile() ?

We import the path core module of node.js.

const path = require(‘path’);

path has a join function . __dirname is a global variable which holds the actual path to project main folder.

path.join(__dirname, ‘views’, ‘add-user.html’); This will refer to the actual file location of add-user html code.

App.js

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
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);

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

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

On running app: npm start

Browser output: localhost:3000/test/add-username

With the use of path module, it will work on any type of operating system without error. Every OS has different way of handling path, so path module takes care of it.

raja
Published on 13-May-2020 17:04:18
Advertisements