HTTP协议
什么是http协议
http协议:超文本传输协议,是通用的、无状态的、与传输数据无关的协议(工作在应用层)
它是一个基于"请求"与"响应"的协议。在计算机领域内专门在两点之间传输文字、图片、音频、视频等超文本数据的约定和规范。
http:// 用于客户端向服务端发送请求,服务端对客户端进行响应。
服务器与客户端的交互过程
(1)客户端与服务器建立TCP连接(所以说HTTP协议是基于TCP协议实现的)
有关TCP协议及TCP连接请浏览历史博客:https://blog.csdn.net/weixin_53186633/article/details/120514627
(2)客户端向服务器发送http请求信息(请求报文)
(3)服务器向客户端返回http响应信息(响应报文)
(4)关闭HTTP连接
例如:
(网络运营):在浏览器输入一个网址:http://www.baidu.com
www.baidu.com是一个域名,通过DNS服务器(DNS:专门用来管理域名和IP地址对应关系的系统)解析之后,知道这个域名对应的IP地址。
然后客户端与这个IP地址对应的服务器建立TCP连接,向服务器发送请求(在这里相当于请求的是百度网站的首页),当服务器接收到请求之后,就将网站首页的文件(例如index.html等)发送(响应)到浏览器,经过浏览器的解析器解析,将标签、js等信息解析出来,展示在网页上。
Node实现http
(1)导入http模块
const http = require('http');
(2)创建http服务器
http.Server类
:提供了实现http服务器的基本框架
http.Server类实现的主要事件有:
request
:当有请求发生时触发该事件,该事件被触发后,其对应的回调函数有request和response两个参数,分别表示请求和响应。
connect
:客户端发出http请求时触发
主要方法:
createServer()
:创建http服务
server.listen()
:启动http服务器监听连接
const http = require('http')
const server = http.createServer((req,res)=>{
console.log('请求地址:'+req.url)
res.write('<h2>Request succeed!</h2>')
res.end()
})
server.listen(8888,()=>{
console.log('服务器在8888端口进行监听')
})
(3)创建http客户端
const http = require('http')
const querystring = require('querystring') //用于获取请求参数
//创建请求数据
const postData=querystring.stringify({'msg':'你好,我是http客户端'})
//创建请求配置信息
const options = {
hostname:'127.0.0.1', //服务器地址
port:8888, //端口
path:'/upload', //请求资源地址
method:'post', //请求方式
headers:{ //请求头信息
'Content-type':'application/x-www-form-urlencoded;charset=utf-8',
'Content-type':Buffer.byteLength(postData)
}
}
const req = http.request(options,(res)=>{
console.log(`状态码:${res.statusCode}`)
console.log(`响应头信息:${JSON.stringify(res.headers)}`)
res.setEncoding('utf8')
res.on('data',chunk=>{
console.log('响应体:'+chunk)
})
res.on('end',()=>{
console.log('没有响应数据,请求结束')
})
res.on('error',(err=>{
console.log(err)
}))
})
req.write(postData) //将数据写入到请求体中
req.end()