In this section, we will delve into how to handle HTTP requests and responses in Node.js. This is a fundamental skill for building web servers and APIs. We will cover the following topics:
- Understanding HTTP Requests and Responses
- Creating a Simple HTTP Server
- Handling Different HTTP Methods
- Parsing Request Data
- Sending Responses
- Understanding HTTP Requests and Responses
HTTP Requests
An HTTP request is a message sent by a client to a server to request data or perform an action. It consists of:
- Request Line: Contains the HTTP method (GET, POST, etc.), the URL, and the HTTP version.
- Headers: Provide metadata about the request (e.g., content type, user agent).
- Body: Contains data sent to the server (used in methods like POST).
HTTP Responses
An HTTP response is a message sent by a server to a client in response to an HTTP request. It consists of:
- Status Line: Contains the HTTP version, status code, and status message.
- Headers: Provide metadata about the response (e.g., content type, content length).
- Body: Contains the data sent back to the client.
- Creating a Simple HTTP Server
Let's start by creating a simple HTTP server that listens for requests and sends back a basic response.
const http = require('http'); // Create an HTTP server const server = http.createServer((req, res) => { // Set the response header res.writeHead(200, { 'Content-Type': 'text/plain' }); // Send the response body res.end('Hello, World!\n'); }); // The server listens on port 3000 server.listen(3000, () => { console.log('Server is listening on port 3000'); });
Explanation
http.createServer
: Creates an HTTP server that listens for requests.req
: Represents the incoming request.res
: Represents the outgoing response.res.writeHead
: Sets the response status code and headers.res.end
: Ends the response and sends the data.
- Handling Different HTTP Methods
Different HTTP methods (GET, POST, PUT, DELETE) are used for different types of operations. Let's handle GET and POST requests.
const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Received a GET request\n'); } else if (req.method === 'POST') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Received a POST request\n'); } else { res.writeHead(405, { 'Content-Type': 'text/plain' }); res.end('Method Not Allowed\n'); } }); server.listen(3000, () => { console.log('Server is listening on port 3000'); });
Explanation
req.method
: Checks the HTTP method of the request.405
: Status code for "Method Not Allowed".
- Parsing Request Data
To handle data sent in a POST request, we need to parse the request body.
const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'POST') { let body = ''; // Collect data chunks req.on('data', chunk => { body += chunk.toString(); }); // End of data req.on('end', () => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(`Received data: ${body}\n`); }); } else { res.writeHead(405, { 'Content-Type': 'text/plain' }); res.end('Method Not Allowed\n'); } }); server.listen(3000, () => { console.log('Server is listening on port 3000'); });
Explanation
req.on('data')
: Listens for data chunks.req.on('end')
: Fires when all data has been received.
- Sending Responses
We can send different types of responses, such as JSON, HTML, or plain text.
Sending JSON Response
const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Hello, World!' })); } else { res.writeHead(405, { 'Content-Type': 'text/plain' }); res.end('Method Not Allowed\n'); } }); server.listen(3000, () => { console.log('Server is listening on port 3000'); });
Explanation
JSON.stringify
: Converts a JavaScript object to a JSON string.
Practical Exercise
Exercise
- Create an HTTP server that handles GET and POST requests.
- For GET requests, respond with a JSON object containing a greeting message.
- For POST requests, parse the request body and respond with the received data in JSON format.
Solution
const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Hello, World!' })); } else if (req.method === 'POST') { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end') => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ receivedData: body })); }); } else { res.writeHead(405, { 'Content-Type': 'text/plain' }); res.end('Method Not Allowed\n'); } }); server.listen(3000, () => { console.log('Server is listening on port 3000'); });
Common Mistakes
- Not ending the response: Always ensure
res.end()
is called to complete the response. - Incorrect Content-Type: Ensure the
Content-Type
header matches the type of data being sent.
Conclusion
In this section, we learned how to handle HTTP requests and responses in Node.js. We covered creating a simple HTTP server, handling different HTTP methods, parsing request data, and sending various types of responses. These skills are essential for building web servers and APIs. In the next section, we will explore how to serve static files and implement routing in our Node.js applications.
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