Node.js学习笔记(五) http模块

这篇文章我们将会学习 Node 的内置模块 http,http 模块主要用于 搭建 HTTP 服务端和客户端

1、http 服务端

(1)创建服务

http 服务端通过 http.Server 实现,我们可以通过以下两种方法创建一个 http.Server

const http = require('http')
// 方法一
var server = new http.Server()
// 方法二
var server = http.createServer()

(2)绑定事件

http.Server 是一个 基于事件 的服务器,我们需要为不同的事件指定相应的处理函数,即可完成功能

最常用的事件莫过于 request,当服务器获取到请求时,就会触发该事件

事件处理函数接收两个参数,分别对应 http.IncomingMessagehttp.ServerResponse

server.on('request', function(message, response) {
    console.log(message instanceof http.IncomingMessage) // true
    console.log(response instanceof http.ServerResponse) // true
    console.log('收到请求')
})

(3)属性方法

http.Server 还有一些常用的属性和方法,介绍如下:

  • listen():监听连接
  • close():关闭连接
  • setTimeout():设置超时时间
  • listening:是否正在监听连接
  • maxHeadersCount:传入的最大报头数,默认为 2000
  • timeout:套接字超时前的等待时间,默认为 0 ms
  • headersTimeout:接收到完整报头前的等待时间,默认为 60000 ms
  • keepAliveTimeout:在写入最后一个响应之后且在套接字销毁之前的等待时间,默认为 5000 ms
server.listen(8888, '127.0.0.1', function() {
    console.log('server running at http://127.0.0.1:8888')
})

(4)http.IncomingMessagehttp.ServerResponse

http.IncomingMessage 表示接收到的数据对象,常用的属性和方法如下:

属性和方法 描述
aborted 请求是否已经终止
complete 是否已接收到完整信息并成功解析
rawHeaders 原始请求头列表
headers 请求头对象
url URL 字符串
httpVersion HTTP 版本
method 请求方法
statusCode 状态代码
statusMessage 状态信息

http.ServerResponse 表示要发送的响应对象,常用的属性和方法如下:

属性和方法 描述
hasHeader(name) 是否具有特定的响应头
getHeader(name) 获取指定的响应头
getHeaders() 获取所有响应头
getHeaderNames() 获取所有响应头的名称
setHeader(name, value) 设置响应头
removeHeader(name) 删除响应头
setTimeout(msecs[, callback]) 设置超时时间
writeHead(statusCode[, statusMessage][, headers]) 发送响应头
write(chunk[, encoding][, callback]) 发送响应体
end([data[, encoding]][, callback]) 所有数据已经发送完毕
headersSent 是否已经发送响应头
statusCode 状态代码,默认为 200
statusMessage 状态信息,默认使用状态代码的标准信息

(5)一个完整的例子

// server.js
const http = require('http')
const path = require('path')
const fs = require('fs')
const server = http.createServer()
server.on('request', function(message, response) {
    let url = message.url
    if (url === '/') url = '/index.html'
    fs.readFile(path.join(__dirname, url), function(error, data) {
        if (error) {
            response.writeHead(404, {'Content-Type': 'plain/html'})
        }
        else {
            response.writeHead(200, {'Content-Type': 'text/html'})
            response.write(data)
        }
        response.end()
    })
})
server.listen(8888, '127.0.0.1', function() {
    console.log('server running at http://127.0.0.1:8888')
})
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
    <p>Index Page</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>About</title>
</head>
<body>
    <p>About Page</p>
</body>
</html>

2、http 客户端

(1)创建服务

http 客户端用于发送 HTTP 请求,它是基于 http.request 实现的,创建方法的签名如下:

http.request(options[, callback])
http.request(url[, options][, callback])
  • url:请求地址,类型为 string 或 URL
  • options:请求参数,类型为 object,常用的属性如下:
    • headers<object>:请求头
    • maxHeaderSize<number>:请求头的最大长度,默认为 8192 Bytes
    • method<string>:请求方法,默认为 GET
    • protocol<string>:网络协议,默认为 http:
    • host<string>:请求的域名或者 IP 地址,默认为 localhost
    • hostname<string>:host 的别名,并且 hostname 的优先级高于 host
    • port<number>:请求端口,默认如果有设置 defaultPort,则为 defaultPort,否则为 80
    • path<string>:请求路径,默认为 /
    • timeout<number>:超时时间
  • callback:回调函数
const http = require('http')
let url = 'http://127.0.0.1:8888/index.html'
let request = http.request(url)

http.request 方法返回 http.ClientRequest 对象

(2)绑定事件

http.ClientRequest 对象也是基于事件的,常用的事件如下:

  • 如果请求发送成功,那么依次触发以下事件:socket -> response(data -> end) -> close
  • 如果请求发送失败,那么依次触发以下事件:socket -> error -> close
request.on('response', function(message) {
    console.log(message instanceof http.IncomingMessage) // true
    console.log('收到响应')
})
request.on('error', function(error) {
    console.log(error instanceof Error) // true
    console.log('发生错误')
})

(3)属性方法

http.ClientRequest 对象常用的属性和方法如下:

  • abort():标志请求被终止
  • getHeader(name):获取请求头
  • setHeader(name, value):设置请求头
  • removeHeader(name):删除请求头
  • setTimeout(timeout[, callback]):设置超时时间
  • write(chunk[, encoding][, callback]):发送请求体
  • end([data[, encoding]][, callback]):所有数据已经发送完毕
// 发送数据
const querystring = require('querystring')
request.write(querystring.stringify({
    username: 'wsmrzx',
    password: '123456'
}))
// 发送结束标志
request.end()

(4)一个完整的例子

const http = require('http')
let url = 'http://127.0.0.1:8888/index.html'
let request = http.request(url)
request.on('response', function(message) {
    let html = ''
    message.on('data', function(chunk) {
        html += chunk
    })
    message.on('end', function() {
        console.log(html)
    })
})
request.on('error', function(error) {
    console.log(error.message)
})
request.end()

【 阅读更多 Node.js 系列文章,请看 Node.js学习笔记

猜你喜欢

转载自www.cnblogs.com/wsmrzx/p/12241712.html