HTTP模块

创建一个服务器

  1. 引入HTTP模块
    const http = require('http');
  2. 创建web服务器实例
    http.creatServer()
  3. 为服务器实例绑定request事件
  4. 启动服务器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 导入HTTP模块
const http = require('http');

// 创建web服务器
const server = http.createServer();

// 绑定request事件
server.on('request', (req, res) => {
console.log("有人访问服务器");
// console.log(req, res);
})
// 启动服务器
server.listen(8080, () => {
console.log("服务器在8080端口启动:http://127.0.0.1:8080");
})

绑定request事件中回调函数中有两个参数,

  • req请求对象
    只要服务器收到了客户端的请求,就会调用server.on()的方法为服务器绑定request事件处理函数。
    req参数包含了与客户端相关的数据和属性。
    比如:
  1. req.url:客户端请求的URL地址
  2. req.method:客户端请求的方法
  • res响应对象
    通过使用res.end()方法向客户端返回内容,并且结束这一次请求

设置请求头,解决中文乱man问题。

根据不同的请求url返回不同的html内容

核心步骤:

  1. 获取请求的url地址。req.url
  2. 设置默认的响应内容 404 not found
  3. 判断用户请求的路径是否为/或者/index.html首页
  4. 判断用户请求的是否为/about.html关于页面
  5. 设置Content-Type响应头,防止中文乱码
  6. res.end()把内容响应给客户端