What is HTTP module in Nodejs?
To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP. To use the HTTP server in node, we need to require the HTTP module. The HTTP module creates an HTTP server that listens to server ports and gives a response back to the client.
- How to import HTTP module
const http = require('http');// import npm module
- Declare Port
const PORT=80; // declare port
- Creating Server
//Creating Server and sending response
const app = http.createServer((req, res)=>{
res.end("First Server created");
})
using http.createserver function we create server and send response using res.end
The http.createServer() method turns your computer into an HTTP server.
The http.createServer() method creates an HTTP Server object.
The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.
- listen server
//listening at port
app.listen(PORT,()=>{
console.log(`Server listening at port ${PORT}`);
})
Syntax
- server.listen(port, hostname, backlog, callback);
Parameter | Description |
---|---|
port | Optional. Specifies the port we want to listen to |
hostname | Optional. Specifies the IP address we want to listen to |
backlog | Optional. Specifies the max length of the queue of pending connections. Default 511 |
callback | Optional. Specifies a function to be executed when the listener has been added |
- Read HTML file and send Responsive to Server
const app = http.createServer((req, res)=>{
fs.readFile(path.join(__dirname,'public','index.html'),(err,data)=>{
if(err)
{
throw err;
}
res.end(data);
})
})
- Send Many HTML file (first check url.req then using this send html file)
const app = http.createServer((req, res)=>{
console.log(req.url);
if(req.url==='/')
{
fs.readFile(path.join(__dirname,'public','index.html'),(err,data)=>{
if(err)
{
throw err;
}
res.end(data);
})
}
else if(req.url==='/about/')
{
fs.readFile(path.join(__dirname,'public','about.html'),(err,data)=>{
if(err)
{
throw err;
}
res.end(data);
})
}
})
//listening at port
app.listen(PORT,()=>{
console.log(`Server listening at port ${PORT}`);
})
- Sending CSS Javascript Html and all file on server (mini site )
const http = require('http');// import npm module
const fs = require('fs');
const path = require('path');
const PORT = 80; // declare port
//Creating Server and sending response
const app = http.createServer((req, res) => {
//collecting path using req.url
let filepath = path.join(__dirname, 'public', (req.url === '/' ?
'index.html' : req.url));
//declare content type
let contentType = 'text/html';
// finding extension of file
let ext = path.extname(filepath);
//no extension in file send .html
if (!ext) {
filepath += '.html';
}
//using switch case making content type
switch (ext) {
case ".css": contentType = 'text/css'; break;
case ".js": contentType = 'text/javascript'; break;
default: contentType = 'text/html';
}
//reading file from filepath
fs.readFile(filepath, (err, content) => {
//if errr in send filepath conent
if(err) {
fs.readFile(path.join(__dirname, 'public', 'error.html'),
(err, data) => {
//if errr send error.html file
if(err) {
res.writeHead(500)
res.end('Error!!!')
}
// //if errr send error.html file
else {
res.writeHead(404, {
'Content-Type': contentType
})
res.end(data)
}
})
}
//if no errr in send filepath conent
else {
res.writeHead(200, {
'Content-Type': contentType
})
res.end(content)
}
})
})
//listening at port
app.listen(PORT, () => {
console.log(`Server listening at port ${PORT}`);
})
more about http module Click here
No comments:
Post a Comment