第七章:HTTP服务器
简要说明
在本章中,我们将学习如何使用Node.js创建一个简单的HTTP服务器。HTTP服务器是Web应用程序的基础,它负责接收客户端的请求并返回相应的响应。通过本章的学习,你将掌握如何使用Node.js内置的http
模块来创建和管理HTTP服务器,并处理基本的HTTP请求和响应。
关键知识点
1. http
模块的使用
Node.js提供了一个内置的http
模块,用于创建HTTP服务器和客户端。要使用http
模块,首先需要引入它:
const http = require('http');
http
模块提供了创建服务器、处理请求和发送响应的方法。它是构建Web应用程序的核心模块之一。
2. 创建HTTP服务器
使用http.createServer()
方法可以创建一个HTTP服务器。该方法接受一个回调函数作为参数,该回调函数会在每次有请求到达服务器时被调用。回调函数有两个参数:request
和response
,分别代表HTTP请求和HTTP响应。
以下是一个简单的HTTP服务器示例:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
在这个示例中,我们创建了一个HTTP服务器,它监听3000端口。当有请求到 达时,服务器会返回一个状态码为200的响应,内容为Hello, World!
。
3. 处理HTTP请求和响应
在HTTP服务器中,request
对象包含了客户端请求的所有信息,如请求方法、URL、请求头等。response
对象用于向客户端发送响应。
处理请求
可以通过request
对象获取请求的详细信息。例如,获取请求的URL:
const http = require('http');
const server = http.createServer((req, res) => {
console.log(`Request URL: ${req.url}`);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Request received\n');
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
在这个示例中,每次请求到达时,服务器都会在控制台打印请求的URL。
发送响应
response
对象用于向客户端发送响应。可以使用res.writeHead()
方法设置响应头,使用res.write()
方法写入响应体,最后使用res.end()
方法结束响应。
以下是一个根据请求URL返回不同响应的示例:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the homepage!\n');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About us\n');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Page not found\n');
}
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
在这个示例中,服务器根据请求的URL返回不同的响应内容。如果请求的URL是/
,则返回欢迎信息;如果请求的URL是/about
,则返回关于信息;否则返回404错误。
总结
在本章中,我们学习了如何使用Node.js的http
模块创建一个简单的HTTP服务器,并处理基本的HTTP请求和响应。通过本章的学习,你应该能够理解HTTP服务器的基本工作原理,并能够使用Node.js构建简单的Web应用程序。
在下一章中,我们将进一步探讨如何处理更复杂的HTTP请求和响应,以及如何使用Express框架简化Web应用程序的开发。