Http模块

Web服务器

当应用程序(客户端)需要某一个资源时,可以向一个台服务器,通过Http请求获取到这个资源;提供资源的这个服务器,就是一个Web服务器;

有很多开源的Web服务器:Nginx、Apache(静态)、Apache Tomcat(静态、动态)、Node.js

创建Web服务器

1
2
3
4
5
6
7
8
9
10
11
const http = require('http');

//创建一个web服务器
const server = http.createServer((request,response)=>{
console.log('服务器中处理函数被调用');
response.end("Hello Server")
})
//启动服务器 并且指定端口号和主机
server.listen(8000,'0.0.0.0',()=>{
console.log("服务器启动成功");
})

使用nodemon工具可以实施实时更新 ··用nodemon运行

创建服务器方式:

1
2
3
4
5
6
const server2 =  http.createServer((request,response)=>{
response.end("Hello Server")
})
server2.listen(8001,()=>{
console.log('s2启动成功');
})
1
2
3
4
5
6
const server2 = new http.Server((req,res)=>{
res.end("server2")
})
server2.listen(8001,()=>{
console.log("server2启动成功");
})

本质上是一样的 源码中的createServer就是返回了一个new http.Server

监听主机和端口号

Server通过listen方法来开启服务器,并且在某一个主机和端口上监听网络请求:

  • 当我们通过 ip:port的方式发送到我们监听的Web服务器上时
  • 我们就可以对其进行相关的处理

listen函数有三个参数 (实际上是四个 不过那一个不太常用)

  • 端口port: 可以不传, 系统会默认分配端, 可以写入到环境变量中;
  • 主机host: 通常可以传入localhost、ip地址127.0.0.1、或者ip地址0.0.0.0,默认是0.0.0.0
    • localhost:本质上是一个域名,通常情况下会被解析成127.0.0.1;
    • 127.0.0.1:回环地址(Loop Back Address),表达的意思其实是我们主机自己发出去的包,直接被自己接收
      • 正常的数据库包经常 应用层 - 传输层 - 网络层 - 数据链路层 - 物理层 ;
      • 而回环地址,是在网络层直接就被获取到了,是不会经常数据链路层和物理层的;
      • 比如我们监听 127.0.0.1时,在同一个网段下的主机中,通过ip地址是不能访问的;
    • 0.0.0.0:
      • 监听IPV4上所有的地址,再根据端口找到不同的应用程序
      • 比如我们监听 0.0.0.0时,在同一个网段下的主机中,通过ip地址是可以访问的;
  • 回调函数:服务器启动成功时的回调函数;

request对象

__request对象中封装了客户端给服务器传过来的所有信息

  • url 本次请求的URL,服务器需要根据不同的URL进行不同的处理;
  • method 本次请求的请求方式,比如GET、POST请求传入的参数和处理的方式是不同的
  • headers 本次请求的headers中也会携带一些信息,比如客户端信息、接受数据的格式、支持的编码格式等
URL的处理

客户端在发送请求时,会请求不同的数据,那么会传入不同的请求地址

服务器根据不同的请求地址做出不同的响应

1
2
3
4
5
6
7
if(request.url==='/login'){
response.end('欢迎回来')
}else if(req.url === '/users'){
response.end('用户列表')
}else{
response.end('错误请求')
}

但是如果有额外的query 例如 login?username=hyp&password=123

使用内置模块url 对 url解析

  • url.parse(request.url)

要获取query信息 使用一个内置模块querystring

  • const{username,password} = qs.parse(query)
method的处理

Restful规范(设计风格)中,我们对于数据的增删改查应该通过不同的请求方式:

  • GET:查询数据;

  • POST:新建数据;

  • PATCH:更新数据;

  • DELETE:删除数据;

所以,我们可以通过判断不同的请求方式进行不同的处理。

  • 比如创建一个用户:
  • 请求接口为 /users;
  • 请求方式为 POST请求;
  • 携带数据 username和password;

通过request.on(‘data’,(data)=>{})拿到body中的数据

因为body中的数据通过的方式写入 所以监听data事件 获取数据

1
2
3
4
5
request.setEncoding('utf-8')      //或者用toString方法
request.on('data',(data)=>{
const{username,password} = JSON.parse(data)
console.log(username,password);
})

将JSON字符串格式转成对象类型,通过JSON.parse方法即可。

headers属性

  • content-type 是本次请求携带的数据的类型
    • application/json表示是一个json类型;
    • text/plain表示是文本类型;
    • application/xml表示是xml类型;
    • multipart/form-data表示是上传文件;
  • content-length 文件大小和长度
  • connection: ‘keep-alive’
    • http是基于TCP协议的,但是通常在进行一次请求和响应结束后会立刻中断;
    • 在http1.0中,如果想要继续保持连接:
      • 浏览器需要在请求头中添加 connection: keep-alive;
      • 服务器需要在响应头中添加 connection:keey-alive;
      • 当客户端再次放请求时,就会使用同一个连接,直接一方中断连接;
    • 在http1.1中,所有连接默认是 connection: keep-alive的;
      • 不同的Web服务器会有不同的保持 keep-alive的时间;
      • Node中默认是5s;
  • accept-encoding:
    • 告知服务器,客户端支持的文件压缩格式,比如js文件可以使用gzip编码,对应 .gz文件
  • accept
    • 告知服务器,客户端可接受文件的格式类型;
  • user-agent
    • 客户端相关的信息;

Response

返回响应结果

如果我们希望给客户端响应的结果数据,可以通过两种方式:

  • Write方法:这种方式是直接写出数据,但是并没有关闭流;

  • end方法:这种方式是写出最后的数据,并且写出后会关闭流;

如果我们没有调用 end和close,客户端将会一直等待结果, 所以客户端在发送网络请求时,都会设置超时时间

返回状态码

Http状态码(Http Status Code)是用来表示Http响应状态的数字代码:

  • Http状态码非常多,可以根据不同的情况,给客户端返回不同的状态码;

设置状态码

  • 方式1: 直接给属性赋值

    • response.statusCode = 401
  • 方式2: 和Head一起设置

    • response.writeHead(503,{})
响应头文件
  • 返回头部信息,主要有两种方式:

    • res.setHeader:一次写入一个头部信息;
    • res.writeHead:同时写入header和status;
  • Header设置 Content-Type有什么作用呢?

    • 默认客户端接收到的是字符串,客户端会按照自己默认的方式进行处理;

http请求

axios库: 既支持前端(xmlhttprequest) 又支持Node中发送网络请求(http模块)

  • 发送get请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const http = require('http');
    //get
    http.get('http://localhost:8888',(res)=>{
    res.on('data',(data)=>{
    console.log(data.toString());
    })
    res.on('end',()=>{
    console.log("获取到所有结果");
    })
    })
  • 发送·post请求有点不一样

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    //post
    const req = http.request({
    method: 'POST',
    hostname: 'localhost',
    port:8888
    },(res)=>{
    res.on('data',(data)=>{
    console.log(data.toString());
    })
    res.on('end',()=>{
    console.log("获取到所有结果");
    })
    })

    req.end() //必须

http文件上传

在postman 请求体里 form-data上传文件 但是如下代码的做法是错误因为写入的字节流中包含的不止是图片的信息,还包含很多描述信息 不能直接写入,所以生成的图片是不能正常呈现的

  • 错误做法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const server = http.createServer((req,res)=>{
if(req.url==='/upload'){
if(req.method==='POST'){
const fileWriter = fs.createWriteStream('./foo.png',{flags:'a+'})
// req.pipe(fileWriter)
req.on('data',(data)=>{
console.log(data);
fileWriter.write(data)
})
req.on('end',()=>{
console.log("文件上传成功");
res.end('文件上传成功')
})
}
}
}).listen(8000,()=>{
console.log("文件上传服务器开启成功");
})
  • 正确做法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const server = http.createServer((req,res)=>{
if(req.url==='/upload'){
if(req.method==='POST'){

//图片文件必须设置成二进制编码
req.setEncoding('binary')
let body='';
//获取content-type中的binary的值
const boundary = req.headers['content-type'].split(";")[1].replace(" boundary=","")
req.on('data',(data)=>{
body += data
})

req.on('end',()=>{
console.log(body);
//处理body
// 首先 获取image/png的位置
const payload = qs.parse(body,"\r\n",":")
const type = payload["Content-Type"]
console.log(type);
//开始在image/png的位置截取
const typeIndex = body.indexOf(type)
const typeLength = type.length
let imageData = body.substring(typeIndex+typeLength)

//将中间的两个空格去掉
imageData = imageData.replace(/^\s\s*/,'')

//将最后的boundary去除
imageData = imageData.substring(0,imageData.indexOf(`--${boundary}--`))
//上传文件
fs.writeFile('./boo.png',imageData,'binary',(err)=>{
res.end('文件上传成功')
})

})
}
}
}).listen(8000,()=>{
console.log("文件上传服务器开启成功");
})