Skip to content

Http 模块

标签:Node
创建时间:2022/10/02 08:24:36

定义

  1. HTTP:超文本传输协议。
  2. HTTP 是浏览器与服务器直接的协议。
  3. 浏览器 ---> 服务器:请求,产生请求报文
  4. 服务器 ---> 浏览器:响应,产生响应报文

请求报文

  1. 请求行
  2. 请求头
  3. 请求体

响应报文

  1. 响应行

    • 200 - 成功

    • 403 - 禁止请求

    • 404 - 找不到资源

    • 500 - 服务器内部错误

      | 状态码 | 含义 | | :----: | :--------: | | 1xx | 信息响应 | | 2xx | 成功响应 | | 3xx | 重定向消息 | | 4xx | 客户端错误 | | 5xx | 服务端错误 |

  2. 响应头

  3. 响应体

创建 HTTP 服务

  1. 引入 http 模块

  2. 创建服务对象

  3. 配置端口

    js
    const http = require('http');
    
    // 创建服务对象
    const server = http.createServer((req, res) => {
        // rt:请求报文
        // re:响应报文
        res.end('Hello');
    });
    
    // 配置端口,启动服务
    server.listen(9000, () => {
        console.log('服务已启动……');
    })
  4. 注意事项

    • 启动 HTTP 服务后,不支持热更新,需要重启服务。

    • 响应内容中使用中文会乱码,可如下设置

      js
      const server = http.createServer((req, res) => {
          res.setHeader('content-type', 'text/html;charset=utf-8')
          res.end('你好');
      });
    • 若端口被占用程序跑不起来,会报错。可在资源监视器中查看端口占用情况。

提取 HTTP 报文

说明API
获取请求方式res.method
获取请求 URLres.url
获取 HTTP 协议版本号res.httpVersion
获取请求头res.headers

提取请求体中的参数

js
const http = require('http');

// 创建服务对象
const server = http.createServer((req, res) => {
    let body = '';

    // 绑定 data 事件
    req.on('data', e => {
        body += e;
    });

    // 绑定 end 事件
    req.on('end', e => {
        console.log(body);
        res.end('Http')
    })
});

// 配置端口,启动服务
server.listen(9000, () => {
    console.log('服务已启动……');
})

提取 URL 中的参数

  1. 方式一:不推荐

    js
    const http = require('http');
    const url = require('url');
    
    // 创建服务对象
    const server = http.createServer((req, res) => {
        let e = url.parse(req.url, true);
        let { account, password } = e.query;
        console.log(`账号:${account}`);
        console.log(`密码:${password}`);
        res.end('Hello');
    });
    
    // 配置端口,启动服务
    server.listen(9000, () => {
        console.log('服务已启动……');
    })
  2. 方式二:推荐

    js
    const http = require('http');
    const url = require('url');
    
    // 创建服务对象
    const server = http.createServer((req, res) => {
        let url = new URL(req.url, 'http://127.0.0.1:9000');
        console.log(`账号:${url.searchParams.get('account')}`);
        console.log(`密码:${url.searchParams.get('password')}`);
        res.end('Node');
    });
    
    // 配置端口,启动服务
    server.listen(9000, () => {
        console.log('服务已启动……');
    })

基于 MIT 许可发布