http模块是node中的核心成员之一,是客户端与服务端交互的基础。http模块不仅可以以极简的方式构建一个服务,还可以发起一个请求;来个简单的栗子:
const http = require('http'); //引入http模块
http.createServer((req, res) => { //创建一个Server对象,与new Server()功能相同
res.writeHead(200, { //返回头信息
'Content-Type': 'text-plain'
});
res.write('hello ')
res.end('world'); //返回正文
}).listen(8000)
上述代码中,通过http.createServer
创建一个服务,并返回状态码200
和纯文本hello world
;
const http = require('http')
let options = {
host: '127.0.0.1',
port: 8000,
method: 'GET'
}
const req = http.request(options, (res) => {
res.setEncoding('utf8') //设置字符编码
let data = ''
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
console.log(`data is ${data}`)
})
})
req.on('error', (e) => {
console.error(`请求遇到问题: ${e.message}`);
});
req.end() //http.request需要手动调用req.end()
上述代码中,通过http发起一个服务,并打印出服务器返回的值。
通过上述代码可以看到,node以一种极简的方式创建服务,并发起请求;
剖析服务端代码
通过res.writeHead()
设置响应的头信息,
- 参数1:必选,一个三位数的 HTTP 状态码,如
200
、404
- 参数2:可选,状态描述,如:
Content-Type
、Content-Length
- 参数3:可选,响应头
通过res.write()
返回数据;注意:node中没有res.send()函数,send函数为express中提供的返回数据的接口;
通过res.end()
结束发送数据,如果该函数指定了data,则先发送数据,再终止res;
通过server.listen()
开启http服务器监听某个端口;
剖析客户端代码
通过http.request()
请求服务,
- 参数1:必须,Object|String|URL
,包含host
、hostname
、method
、path
(请求的路径,如/home
)等;
- 参数2::可选, Function
通过res.setEncoding()
设置返回的字符编码,当有返回值时,触发data
事件;当返回值结束时,触发end
事件;
与http.request()
类似的函数有http.get()
,唯一的一点不同是,http.get()
自动调用req.end()
更详细的api请参考:nodejs官网_http模块
参考资料:
[1]:Node.js中文网