Our first program will create a basic HTTP server. Here’s the full source code:
To run the server:
Access the /hello route:
This example demonstrates how to create a basic HTTP server in Node.js. We use the built-in http module to create the server and define routes.
In Node.js, we define handler functions that take a request and response object. These are similar to the concept of handlers in other web frameworks.
We set up two routes: /hello which returns a simple greeting, and /headers which echoes back all the request headers.
The createServer method is used to create the HTTP server, and we define a callback function that handles all incoming requests. Inside this function, we check the URL of the request and call the appropriate handler.
Finally, we call server.listen to start the server on port 8090.
This setup provides a simple and flexible way to create HTTP servers in Node.js, allowing you to easily define different routes and their corresponding behaviors.