How can you create a simple HTTP server using Node.js?
How to create a simple HTTP server using Node.js?
24428-Sep-2023
Updated on 04-Oct-2023
Home / DeveloperSection / Forums / How to create a simple HTTP server using Node.js?
How can you create a simple HTTP server using Node.js?
Aryan Kumar
04-Oct-2023Creating a simple HTTP server using Node.js is relatively straightforward. You can use the built-in http module to achieve this. Here's a step-by-step guide on how to create a basic HTTP server in Node.js:
Import the http Module: First, you need to import the http module, which comes bundled with Node.js.
Create an HTTP Server: Next, create an HTTP server using the http.createServer() method. You'll need to provide a callback function that will be called whenever a request is received.
Define Request Handling Logic: Inside the callback function, you can define the logic for handling incoming HTTP requests (req) and sending responses (res). For a simple example, you can send a "Hello, World!" response.
Specify the Listening Port and Host: To make the server listen for incoming requests, specify the port number and, optionally, the host (e.g., 'localhost').
Start the Server: Finally, call the server.listen() method to start the HTTP server and make it listen on the specified port and host.
Testing the Server: You can open a web browser and visit http://localhost:3000/ (or the host and port you specified) to see your "Hello, World!" response. You can also use tools like curl or Postman to test the server from the command line.
Here's the complete code for a simple HTTP server:
This code creates a basic HTTP server that responds with "Hello, World!" to any incoming requests. You can expand upon this foundation to build more complex web applications and APIs in Node.js.