Node.js provides a built-in module called HTTP which allows developers to create web servers and handle HTTP requests and responses. This module is essential for building server-side applications in Node.js.
The HTTP module can be used to create a simple server that listens for requests on a specified port. This is the foundation for any web application built using Node.js.
Once a server is created, it can handle incoming requests and send appropriate responses. This involves parsing request data and sending back data in the form of HTML, JSON, etc.
Configuring the server to handle different routes and methods (GET, POST, etc.) is crucial for building RESTful services and APIs.
Proper error handling ensures that the server can gracefully handle unexpected situations without crashing.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
This code sets up a basic HTTP server that listens on localhost (127.0.0.1) at port 3000. When a request is made, it responds with "Hello, World!". This is the simplest form of a Node.js server.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Home Page\n');
} else if (req.url === '/about') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('About Page\n');
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Page Not Found\n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
This example demonstrates how to handle different routes using the HTTP module. The server responds with different messages based on the URL path. If the path doesn't match any predefined route, it returns a 404 error.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
const data = { message: 'Hello, JSON!' };
res.end(JSON.stringify(data));
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
This code snippet shows how to serve JSON data using the HTTP module in Node.js. The server sends a JSON object as a response, which can be useful for APIs returning structured data.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(`Received data: ${body}\n`);
});
} else {
res.statusCode = 405;
res.setHeader('Content-Type', 'text/plain');
res.end('Method Not Allowed\n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
This example illustrates how to handle POST requests in a Node.js server. The server listens for data being sent in the request body and outputs it once the entire body has been received.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
try {
if (req.url === '/error') {
throw new Error('Forced error');
}
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('No errors here!\n');
} catch (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'text/plain');
res.end(`Server Error: ${err.message}\n`);
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
This code demonstrates basic error handling in a Node.js HTTP server. It includes a route that deliberately throws an error, showing how to catch and respond to exceptions gracefully.
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies