Node.js-核心模块之http模块

HTTP 模块是 Node.js 核心模块之一,提供了创建 HTTP 服务器和客户端的功能。以下是 HTTP 模块的一些主要内容和使用方法的详细讲解。

创建 HTTP 服务器

  1. http.createServer([requestListener]): 创建一个 HTTP 服务器实例。requestListener 是一个处理请求的回调函数,每当有请求进来时就会被调用。

    const http = require('http');
    
    const server = http.createServer((req, res) => {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello, World!');
    });
    
    server.listen(3000, '127.0.0.1', () => {
      console.log('Server listening on port 3000');
    });
    

处理 HTTP 请求和响应

  1. request 对象: 表示客户端的请求,提供了关于请求的信息。

    const http = require('http');
    
    const server = http.createServer((req, res) => {
      console.log('Request Method:', req.method);
      console.log('Request URL:', req.url);
    
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello, World!');
    });
    
    server.listen(3000, '127.0.0.1', () => {
      console.log('Server listening on port 3000');
    });
    
  2. response 对象: 表示服务器对客户端请求的响应,通过该对象可以发送响应数据。

    const http = require('http');
    
    const server = http.createServer((req, res) => {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello, World!');
    });
    
    server.listen(3000, '127.0.0.1', () => {
      console.log('Server listening on port 3000');
    });
    

处理 POST 请求

  1. 处理 POST 请求: 监听 dataend 事件来获取 POST 请求的数据。

    const http = require('http');
    
    const server = http.createServer((req, res) => {
      if (req.method === 'POST') {
        let data = '';
    
        req.on('data', (chunk) => {
          data += chunk;
        });
    
        req.on('end', () => {
          console.log('Received data:', data);
          res.writeHead(200, {'Content-Type': 'text/plain'});
          res.end('Data received successfully.');
        });
      } else {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('Not Found');
      }
    });
    
    server.listen(3000, '127.0.0.1', () => {
      console.log('Server listening on port 3000');
    });
    

创建 HTTP 客户端

  1. http.request(options[, callback]): 创建一个 HTTP 客户端实例。options 定义了请求的参数,callback 是一个回调函数,在响应可用时被调用。

    const http = require('http');
    
    const options = {
      hostname: 'www.example.com',
      port: 80,
      path: '/',
      method: 'GET',
    };
    
    const req = http.request(options, (res) => {
      let data = '';
    
      res.on('data', (chunk) => {
        data += chunk;
      });
    
      res.on('end', () => {
        console.log('Response:', data);
      });
    });
    
    req.end();
    

完整的 HTTP 客户端和服务器

  1. 完整的 HTTP 客户端和服务器: 将上述的创建服务器和客户端的功能结合使用。

    const http = require('http');
    
    // 创建 HTTP 服务器
    const server = http.createServer((req, res) => {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello, World!');
    });
    
    server.listen(3000, '127.0.0.1', () => {
      console.log('Server listening on port 3000');
    });
    
    // 创建 HTTP 客户端
    const clientOptions = {
      hostname: '127.0.0.1',
      port: 3000,
      path: '/',
      method: 'GET',
    };
    
    const clientReq = http.request(clientOptions, (res) => {
      let data = '';
    
      res.on('data', (chunk) => {
        data += chunk;
      });
    
      res.on('end', () => {
        console.log('Client Response:', data);
      });
    });
    
    clientReq.end();
    
  • 22
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[猫玖]

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值