Node.js makes it easy to handle HTTP requests and responses. This tutorial will walk you through how to set up a basic HTTP server and interact with requests and responses using the built-in `http` module.
Node.js HTTP Request & Response
1. Introduction to HTTP in Node.js
Node.js uses the `http` module to create HTTP servers and handle client requests. This allows Node.js to serve web pages and API responses.
2. Creating a Simple HTTP Server
First, let's create a basic HTTP server that listens for incoming requests and sends back a response:
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, Node.js!');
}).listen(8080, () => {
console.log('Server running at http://localhost:8080/');
});
This code creates a server that listens on port 8080. When accessed, it sends a plain-text response: "Hello, Node.js!"
3. Handling HTTP Requests
When a client makes a request, Node.js can inspect the request details, such as the URL, method, and headers. Here's how you can handle incoming requests:
const http = require('http');
http.createServer((req, res) => {
console.log('Request received');
console.log('Method:', req.method);
console.log('URL:', req.url);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Request details logged');
}).listen(8080, () => {
console.log('Server running at http://localhost:8080/');
});
This example logs the request method and URL to the console whenever the server receives a request.
4. Sending HTTP Responses
Node.js provides the `res` object to send responses to clients. You can set the response status code and content type, and send data back to the client:
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'application/json'});
const responseObj = { message: 'Hello, JSON!' };
res.end(JSON.stringify(responseObj));
}).listen(8080, () => {
console.log('Server running at http://localhost:8080/');
});
This sends a JSON response with a message "Hello, JSON!" when the client accesses the server.
5. Handling Query Parameters
HTTP requests can include query parameters in the URL. Here's how to parse and handle them:
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
console.log('Query Parameters:', query);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Query parameters received');
}).listen(8080, () => {
console.log('Server running at http://localhost:8080/');
});
This example uses the `url` module to parse query parameters from the URL and log them to the console.
6. Conclusion
Handling HTTP requests and responses in Node.js is fundamental for building web applications and APIs. With the built-in `http` module, you can create servers, read request details, and send custom responses. This flexibility is key to building dynamic and interactive web services.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.