<!DOCTYPE html>
How To Create an HTTP or Express.js Server in Node.js
In this tutorial, we will learn how to create a simple web server using Node.js. Node.js is a popular runtime environment that allows you to run JavaScript code on the server side.
Creating an HTTP Server
To create an HTTP server in Node.js, you can use the built-in http module. Here is an example of how to create a simple HTTP server:
// Import the http module
const http = require('http');
// Create a server object
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
});
// Set the port the server will listen on
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
This code creates an HTTP server that listens on port 3000 and responds with a simple “Hello World!” message when a request is made to it.
Creating an Express.js Server
Express.js is a popular web application framework for Node.js. It makes it easy to create web servers and handle HTTP requests. Here is an example of how to create a simple Express.js server:
// Import the express module
const express = require('express');
// Create an express application
const app = express();
// Define a route handler for the root path
app.get('/', (req, res) => {
res.send('Hello World from Express.js!');
});
// Set the port the server will listen on
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
This code creates an Express.js server that listens on port 3000 and responds with a simple “Hello World from Express.js!” message when a request is made to it.
Conclusion
Creating an HTTP or Express.js server in Node.js is a straightforward process. By using the built-in http module or the Express.js framework, you can quickly set up a web server and start handling HTTP requests. This tutorial should serve as a good starting point for building your own web applications with Node.js.