微信登录

核心模块 - http 模块 - 处理 HTTP 请求与响应

Node.js 《核心模块 - http 模块 - 处理 HTTP 请求与响应》

引言

在 Node.js 中,http 模块是其核心模块之一,它为创建 HTTP 服务器和客户端提供了强大的功能。借助 http 模块,我们可以轻松地构建 Web 服务器、API 服务等。本文将深入探讨如何使用 http 模块来处理 HTTP 请求与响应,并给出相应的演示代码。

1. 创建 HTTP 服务器

使用 http 模块创建一个简单的 HTTP 服务器非常容易。以下是一个基本的示例:

  1. const http = require('http');
  2. // 创建服务器
  3. const server = http.createServer((req, res) => {
  4. // 设置响应头
  5. res.writeHead(200, { 'Content-Type': 'text/plain' });
  6. // 发送响应内容
  7. res.end('Hello, World!\n');
  8. });
  9. // 监听端口
  10. const port = 3000;
  11. server.listen(port, () => {
  12. console.log(`Server running at http://localhost:${port}/`);
  13. });

代码解释:

  • require('http'):引入 Node.js 的 http 模块。
  • http.createServer():创建一个 HTTP 服务器实例,它接受一个回调函数作为参数,该回调函数在每次收到请求时都会被调用。
  • res.writeHead(200, { 'Content-Type': 'text/plain' }):设置响应头,状态码为 200(表示成功),内容类型为纯文本。
  • res.end('Hello, World!\n'):发送响应内容并结束响应。
  • server.listen(port, callback):让服务器监听指定的端口,并在服务器启动成功后执行回调函数。

2. 处理不同的请求路径

在实际应用中,我们通常需要根据不同的请求路径来返回不同的响应。以下是一个示例:

  1. const http = require('http');
  2. const server = http.createServer((req, res) => {
  3. if (req.url === '/') {
  4. res.writeHead(200, { 'Content-Type': 'text/plain' });
  5. res.end('Welcome to the home page!\n');
  6. } else if (req.url === '/about') {
  7. res.writeHead(200, { 'Content-Type': 'text/plain' });
  8. res.end('This is the about page.\n');
  9. } else {
  10. res.writeHead(404, { 'Content-Type': 'text/plain' });
  11. res.end('404 Not Found\n');
  12. }
  13. });
  14. const port = 3000;
  15. server.listen(port, () => {
  16. console.log(`Server running at http://localhost:${port}/`);
  17. });

代码解释:

  • req.url:获取请求的 URL 路径。
  • 根据不同的路径返回不同的响应内容,如果路径不存在,则返回 404 错误。

3. 处理 POST 请求

除了 GET 请求,我们还可以处理 POST 请求。以下是一个处理 POST 请求并接收表单数据的示例:

  1. const http = require('http');
  2. const querystring = require('querystring');
  3. const server = http.createServer((req, res) => {
  4. if (req.method === 'POST') {
  5. let body = '';
  6. req.on('data', (chunk) => {
  7. body += chunk.toString();
  8. });
  9. req.on('end', () => {
  10. const formData = querystring.parse(body);
  11. res.writeHead(200, { 'Content-Type': 'text/plain' });
  12. res.end(`Received data: ${JSON.stringify(formData)}\n`);
  13. });
  14. } else {
  15. res.writeHead(405, { 'Content-Type': 'text/plain' });
  16. res.end('Method Not Allowed\n');
  17. }
  18. });
  19. const port = 3000;
  20. server.listen(port, () => {
  21. console.log(`Server running at http://localhost:${port}/`);
  22. });

代码解释:

  • req.method:获取请求的方法(如 GET、POST 等)。
  • req.on('data', callback):监听 data 事件,当有数据传输时,将数据块追加到 body 变量中。
  • req.on('end', callback):监听 end 事件,当数据传输结束时,使用 querystring.parse() 方法将表单数据解析为对象。

4. 总结

功能 代码示例 解释
创建 HTTP 服务器 http.createServer((req, res) => { ... }) 创建一个 HTTP 服务器实例,回调函数处理请求和响应
设置响应头 res.writeHead(statusCode, headers) 设置响应的状态码和头信息
发送响应内容 res.end(content) 发送响应内容并结束响应
获取请求路径 req.url 获取请求的 URL 路径
获取请求方法 req.method 获取请求的方法(如 GET、POST 等)
处理 POST 数据 req.on('data', callback)req.on('end', callback) 监听数据传输事件,接收并处理 POST 数据

结论

Node.js 的 http 模块为我们提供了丰富的功能来处理 HTTP 请求与响应。通过本文的示例,你可以学习到如何创建简单的 HTTP 服务器、处理不同的请求路径以及接收 POST 请求数据。掌握这些知识后,你就可以开始构建自己的 Web 应用和 API 服务了。希望本文对你有所帮助!