Creating a basic HTTP server in Node.js is a fundamental skill for any web developer. Node.js provides a powerful and efficient way to handle server requests and responses, making it a popular choice for building web applications. In this article, we’ll walk through three diverse examples that illustrate how to create an HTTP server in Node.js, each tailored for different use cases. Let’s get started!
This example demonstrates how to create a simple HTTP server that responds with a plain text message. It’s perfect for beginners who want to grasp the basics of HTTP servers in Node.js.
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}/`);
});
localhost
at port 3000
. You can test it by navigating to http://127.0.0.1:3000
in your web browser.res.end
with any text you like!In this example, we will create an HTTP server that sends back a JSON response. This is useful for APIs where you need to return structured data to the client.
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 responseData = { message: 'Hello, JSON!', date: new Date() };
res.end(JSON.stringify(responseData));
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
http://127.0.0.1:3000
, you will receive a JSON object. This is particularly handy for developers building RESTful APIs.responseData
object to include any data relevant to your application.This example showcases how to implement basic routing in your HTTP server. This allows the server to respond differently based on the request URL, making it more versatile.
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');
if (req.url === '/') {
res.end('Welcome to the Home Page!\n');
} else if (req.url === '/about') {
res.end('This is the About Page!\n');
} else {
res.statusCode = 404;
res.end('404 Not Found\n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
/
and /about
, and returns a 404 error for any other routes.These examples of creating a basic HTTP server in Node.js illustrate the versatility and ease of use of Node.js for web development. Whether you’re building a simple application, an API, or a more complex server, these foundational skills will serve you well in your programming journey.