
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Serving HTML Pages from Node.js
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="/https/www.tutorialspoint.com/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="/https/www.tutorialspoint.com/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.