阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > HTTP模块详解

HTTP模块详解

作者:陈川 阅读数:39906人阅读 分类: Node.js

HTTP模块概述

Node.js的HTTP模块是核心模块之一,用于创建HTTP服务器和客户端。它提供了底层的网络通信能力,能够处理HTTP请求和响应。通过这个模块,开发者可以构建Web服务器、代理服务器或任何需要HTTP协议通信的应用。

创建HTTP服务器

使用http.createServer()方法可以快速创建一个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 running at http://localhost:3000/');
});

回调函数接收两个参数:req(请求对象)和res(响应对象)。req包含请求的详细信息,res用于构建和发送响应。

请求对象(req)详解

请求对象reqhttp.IncomingMessage的实例,包含客户端请求的所有信息:

  • req.method: 请求方法(GET, POST等)
  • req.url: 请求的URL路径
  • req.headers: 请求头对象
  • req.httpVersion: HTTP协议版本
const server = http.createServer((req, res) => {
  console.log(`Method: ${req.method}`);
  console.log(`URL: ${req.url}`);
  console.log('Headers:', req.headers);
  
  res.end('Request received');
});

响应对象(res)详解

响应对象reshttp.ServerResponse的实例,用于向客户端发送响应:

  • res.writeHead(statusCode, headers): 设置响应状态码和头
  • res.write(data): 写入响应体
  • res.end([data]): 结束响应,可选发送最后的数据
const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, {
      'Content-Type': 'text/html',
      'Custom-Header': 'SomeValue'
    });
    res.write('<h1>Home Page</h1>');
    res.end();
  } else {
    res.writeHead(404);
    res.end('Not Found');
  }
});

处理请求体数据

对于POST请求,需要监听dataend事件来获取请求体数据:

const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    
    req.on('data', chunk => {
      body += chunk.toString();
    });
    
    req.on('end', () => {
      console.log('Received body:', body);
      res.end('Data received');
    });
  } else {
    res.end('Send a POST request');
  }
});

创建HTTP客户端

HTTP模块也可以用来发起HTTP请求:

const http = require('http');

const options = {
  hostname: 'example.com',
  port: 80,
  path: '/api/data',
  method: 'GET'
};

const req = http.request(options, (res) => {
  console.log(`Status Code: ${res.statusCode}`);
  
  res.on('data', (chunk) => {
    console.log(`Received chunk: ${chunk}`);
  });
});

req.on('error', (error) => {
  console.error('Request error:', error);
});

req.end();

处理HTTPS请求

对于HTTPS请求,需要使用https模块,它与HTTP模块API几乎相同:

const https = require('https');

https.get('https://api.example.com/data', (res) => {
  let data = '';
  
  res.on('data', (chunk) => {
    data += chunk;
  });
  
  res.on('end', () => {
    console.log('Response:', JSON.parse(data));
  });
}).on('error', (err) => {
  console.error('Error:', err);
});

流式处理大文件

HTTP模块天然支持流式处理,适合传输大文件:

const fs = require('fs');
const http = require('http');

http.createServer((req, res) => {
  const fileStream = fs.createReadStream('./large-file.txt');
  
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  
  fileStream.pipe(res);
}).listen(3000);

性能优化技巧

  1. 重用服务器实例:避免频繁创建和销毁服务器
  2. 连接池:客户端请求时重用TCP连接
  3. 压缩:使用zlib模块压缩响应数据
  4. 超时设置:避免长时间挂起的请求
const server = http.createServer();

// 设置超时
server.setTimeout(5000, (socket) => {
  console.log('Request timed out');
  socket.end();
});

server.on('request', (req, res) => {
  // 处理请求
});

实际应用场景

  1. REST API服务:构建轻量级API服务
  2. 代理服务器:转发客户端请求
  3. 静态文件服务器:托管静态资源
  4. WebSocket基础:与ws模块配合实现实时通信
// 简单代理服务器示例
http.createServer((clientReq, clientRes) => {
  const options = {
    hostname: 'target-server.com',
    port: 80,
    path: clientReq.url,
    method: clientReq.method,
    headers: clientReq.headers
  };
  
  const proxyReq = http.request(options, (proxyRes) => {
    clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
    proxyRes.pipe(clientRes);
  });
  
  clientReq.pipe(proxyReq);
}).listen(8080);

错误处理

正确处理HTTP模块可能出现的错误:

const server = http.createServer((req, res) => {
  // 正常处理
});

server.on('clientError', (err, socket) => {
  if (err.code === 'ECONNRESET' || !socket.writable) {
    return;
  }
  
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});

server.on('error', (err) => {
  console.error('Server error:', err);
});

高级配置选项

HTTP服务器和客户端都支持多种配置:

// 自定义HTTP Agent配置
const http = require('http');
const keepAliveAgent = new http.Agent({
  keepAlive: true,
  maxSockets: 10,
  keepAliveMsecs: 60000
});

const options = {
  hostname: 'example.com',
  port: 80,
  path: '/',
  agent: keepAliveAgent
};

http.get(options, (res) => {
  // 处理响应
});

与其他模块集成

HTTP模块常与其他Node.js模块配合使用:

const http = require('http');
const url = require('url');
const querystring = require('querystring');

http.createServer((req, res) => {
  const parsedUrl = url.parse(req.url);
  const query = querystring.parse(parsedUrl.query);
  
  console.log('Path:', parsedUrl.pathname);
  console.log('Query params:', query);
  
  res.end('Check console for URL details');
}).listen(3000);

性能监控

监控HTTP服务器的性能指标:

const server = http.createServer((req, res) => {
  res.end('OK');
});

// 监控连接数
server.on('connection', (socket) => {
  console.log('Active connections:', server._connections);
  
  socket.on('close', () => {
    console.log('Connection closed. Active:', server._connections);
  });
});

HTTP/2支持

Node.js也支持HTTP/2协议:

const http2 = require('http2');
const fs = require('fs');

const server = http2.createSecureServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.crt')
});

server.on('stream', (stream, headers) => {
  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });
  stream.end('<h1>Hello HTTP/2</h1>');
});

server.listen(8443);

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:文件锁机制

下一篇:HTTPS与安全通信

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌