黑马_3、http 模块

1、什么是 http 模块

http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的http.createServer()方法,就能方便的把一台普通的电脑,变成一台 Web 服务器,从而对外提供 Web 资源服务。

如果要希望使用 http 模块创建 Web 服务器,则需要先导入它:
const http=require('http');

2、http 模块的作用

服务器和普通电脑的区别在于,服务器上安装了 web 服务器软件,例如:IIS(asp.net开发用到)、Apache(php开发用到) 等。通过安装这些服务器软件,就能把一台普通的电脑变成一台 web 服务器。

Node.js 中,我们不需要使用 IIS、Apache 等这些第三方 web 服务器软件。因为我们可以基于 Node.js 提供的 http 模块,通过几行简单的代码,就能轻松的手写一个服务器软件,从而对外提供 web 服务。

3、创建最基本的 web 服务器

3.1、 创建 web 服务器的基本步骤

①导入 http 模块
②创建 web 服务器实例
③为服务器实例绑定 request 事件,监听客户端的请求。
④启动服务器

// 1. 导入 http 模块
const http = require('http');
// 2. 创建 web 服务器实例
const server = http.createServer();
// 3. 为服务器实例绑定 request 事件,监听客户端的请求
server.on('request', function (request, response) {
    // request 是请求对象,包含了与客户端相关的数据和属性
    //request.url 是客户端请求的 URL 地址
    const url = request.url;
    // request.method 是客户端请求的 method 类型
    const method = request.method;
    const str = `请求的url是: ${url}, 请求的方式是: ${method}`;
  
    // 调用 response.setHeader() 方法,设置 Content-Type 响应头,解决中文乱码的问题
    response.setHeader('Content-Type', 'text/html; charset=utf-8');
    // 调用 response.end() 方法,向客户端响应一些内容
    response.end(str);

});
// 4. 启动服务器
server.listen(8088, function () {  
  console.log('服务器启动了');
});
posted @ 2022-07-17 21:36  青仙  阅读(81)  评论(0编辑  收藏  举报