项目作者: lcyh

项目描述 :
手写模拟 HTTP的get和post请求
高级语言: JavaScript
项目地址: git://github.com/lcyh/HTTP-get-post.git
创建时间: 2020-09-27T06:54:11Z
项目社区:https://github.com/lcyh/HTTP-get-post

开源协议:

下载


1.TCP/IP 参考模型

tcp 协议传输信息,http 协议解析信息

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/readyState

http://nodejs.cn/api/net.html#net_net_createconnection_options_connectlistener

2.GET
GET 方法意思是获取被请求 URI(Request-URI)指定的信息(以实体的格式)

2.1.1 http-server

  1. const http = require(“http”);
  2. const fs = require(“fs”);
  3. const url = require(“url”);
  4. const path = require(“path”);
  5. const server = http.createServer((req, res) => {
  6. const { pathname } = url.parse(req.url);
  7. if (pathname === “/get.html”) {
  8. console.log(“进来了~~~”);
  9. res.statusCode = 200;
  10. res.setHeader(“Content-Type”, text/html”);
  11. const html = fs.readFileSync(path.join(__dirname, static”, get.html”));
  12. res.end(html);
  13. } else if (pathname === “/get”) {
  14. res.statusCode = 200;
  15. res.setHeader(“Content-Type”, text/plain”);
  16. res.end(“get”);
  17. } else {
  18. res.statusCode = 404;
  19. res.end();
  20. }
  21. });
  22. server.listen(8080, () => {
  23. console.log(“server is running at port 8080”);
  24. });

2.1.2 static/get.html

2.2 请求响应格式

2.2.1 请求
一个请求消息是从客户端到服务器端的,在消息首行里包含方法,资源指示符,协议版本。

  1. Request = Request-Line ; Section 5.1 \*(( general-header ; Section 4.5
  2. | request-header ; Section 5.3
  3. | entity-header CRLF ; Section 7.1
  4. CRLF
  5. [ message-body ] ; Section 4.3
  6. GET /get HTTP/1.1
  7. Host: 127.0.0.1:8080
  8. Connection: keep-alive
  9. name: zhangsan
  10. age: 11
  11. User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36
  12. Accept: /
  13. Accept-Encoding: gzip, deflate, br
  14. Accept-Language: zh-CN,zh;q=0.9,und;q=0.8,en;q=0.7

2.2.2 响应
接收和解析一个请求消息后,服务器发出一个 HTTP 响应消息。

  1. response Status-Line ; \*(( general-header ;
  2. | response-header ;
  3. | entity-headerCRLF ;
  4. CRLF
  5. [ message-body ] ;
  6. HTTP/1.1 200 OK
  7. Context-type: text-plain
  8. Date: Sat, 26 Sep 2020 12:52:29 GMT
  9. Connection: keep-alive
  10. Transfer-Encoding: chunked
  11. 5
  12. get55
  13. 0