一、什么是数据协商呢?
在客户端发送请求给服务端的时候,客户端会声明它想要拿到的数据格式 以及 数据相关的限制。服务器则以此为线索,通过内部算法来选择最佳方案提供给客户端。相关算法与具体的服务器相关,并没有在规范中进行规定。
二、参数介绍
1、客户端
1)Accept
Accept 首部列举了用户代理希望接收的媒体资源的 MIME 类型
2)Accept-Encoding
Accept-Encoding 首部明确说明了(接收端)可以接受的内容编码形式(所支持的压缩算法)
3) Accept- Language
Accept-Language请求头允许客户端声明它可以理解的自然语言,以及优先选择的区域方言
4)User-Agent
User-Agent 首部包含了一个特征字符串,用来让网络协议的对端来识别发起请求的用户代理软件的应用类型、操作系统、软件开发商以及版本号
2、服务端
1)Content-Type
Content-Type 实体头部用于指示资源的MIME类型
2)Content-Encoding
gzip压缩
zlib模块提供通过 Gzip 实现的压缩功能
3) Content-Language
Content-Language是一个 entity header (实体消息首部),用来说明响应的语言类型
3、案例:
const http = require("http");
const config = require("./config/config");
const fs = require("fs");
const zlib = require("zlib");
const server = http.createServer((message,response)=>{
if(message.url === "/"){
fs.readFile("./data.html",(err,data)=>{
response.writeHead(200,"ok",{
"Content-type":"text/html",
"Content-Encoding":"gzip"
})
//zip压缩。
response.end(zlib.gzipSync(data));
})
}
})
server.listen(config.port,config.host,()=>{
console.log(`server is starting at ${config.host}:${config.port}`);
});
data.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
img{
width: 100px;
}
</style>
</head>
<body>
<!--测试文本-->
</body>
</html>
4、测试结果