In this section, we will learn how to create a simple HTTP server using Node.js. This is a fundamental skill for any Node.js developer, as it forms the basis for building web applications and APIs.
Key Concepts
- HTTP Module: Node.js has a built-in module called
http
that allows you to create an HTTP server. - Server Object: The
http.createServer()
method creates an HTTP server object. - Request and Response: The server object listens for HTTP requests and sends back responses.
Step-by-Step Guide
- Import the HTTP Module
First, you need to import the http
module. This module provides the functionality to create an HTTP server.
- Create the Server
Use the http.createServer()
method to create a server. This method takes a callback function as an argument. The callback function is executed each time the server receives a request.
- Handle Requests and Send Responses
Inside the callback function, you can handle the incoming request (req
) and send a response (res
). For this example, we will send a simple "Hello, World!" message.
const server = http.createServer((req, res) => { res.statusCode = 200; // HTTP status code 200: OK res.setHeader('Content-Type', 'text/plain'); // Set the content type to plain text res.end('Hello, World!\n'); // Send the response body });
- Listen on a Port
Finally, you need to specify the port on which the server should listen for incoming requests. Common practice is to use port 3000 for development.
const PORT = 3000; server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
Complete Code Example
Here is the complete code to create a simple HTTP server:
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
Running the Server
- Save the code in a file named
server.js
. - Open your terminal and navigate to the directory where
server.js
is located. - Run the server using the following command:
- Open your web browser and go to
http://localhost:3000
. You should see the message "Hello, World!".
Practical Exercise
Exercise 1: Modify the Response
Modify the server to send an HTML response instead of plain text.
Solution
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end('<h1>Hello, World!</h1>'); }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
Exercise 2: Add Routing
Modify the server to handle different routes. For example, respond with "Welcome to the Home Page" for the root URL (/
) and "About Us" for the /about
URL.
Solution
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); if (req.url === '/') { res.end('<h1>Welcome to the Home Page</h1>'); } else if (req.url === '/about') { res.end('<h1>About Us</h1>'); } else { res.statusCode = 404; res.end('<h1>404 Not Found</h1>'); } }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
Common Mistakes and Tips
- Forgetting to set the Content-Type header: Always set the appropriate
Content-Type
header to inform the client about the type of content being sent. - Not handling different routes: Make sure to handle different routes and provide appropriate responses for each.
- Not closing the response: Always call
res.end()
to close the response and send it to the client.
Conclusion
In this section, you learned how to create a simple HTTP server using Node.js. You now know how to handle requests, send responses, and implement basic routing. This foundational knowledge will be crucial as you move on to more advanced topics in Node.js.
Node.js Course
Module 1: Introduction to Node.js
Module 2: Core Concepts
Module 3: File System and I/O
Module 4: HTTP and Web Servers
Module 5: NPM and Package Management
- Introduction to NPM
- Installing and Using Packages
- Creating and Publishing Packages
- Semantic Versioning
Module 6: Express.js Framework
- Introduction to Express.js
- Setting Up an Express Application
- Middleware
- Routing in Express
- Error Handling
Module 7: Databases and ORMs
- Introduction to Databases
- Using MongoDB with Mongoose
- Using SQL Databases with Sequelize
- CRUD Operations
Module 8: Authentication and Authorization
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with Mocha and Chai
- Integration Testing
- Debugging Node.js Applications
Module 10: Advanced Topics
Module 11: Deployment and DevOps
- Environment Variables
- Using PM2 for Process Management
- Deploying to Heroku
- Continuous Integration and Deployment