http协议

1. 报文

在http请求和响应的过程中,传递的数据块就叫报文,包括要传送的数据和一些附加信息,并且要遵守固定好的格式。

2. 请求报文

1.请求方式

  • get 请求数据
  • post 发送数据

2.请求地址

1 app.on('request', (req, res) => {
2     req.headers // 获取请求报文
3     req.url // 获取请求地址
4     req.method // 获取请求方法
5 }); 

3. 响应报文

1.http状态码

  • 200请求成功
  • 404请求的资源没有被找到
  • 500服务器端错误
  • 400客户端请求有语法错误

2.内容类型

  • text/html
  • text/css
  • application/javascript
  • image/jpeg
  • application/json
 app.on('request', (req, res) => {
     // 设置响应报文
     res.writeHead(200, {
    'Content-Type': 'text/html;charset=utf8‘ }); });

4. GET请求参数

  • 参数被放置在浏览器地址栏中,例如:http://localhost:3000/?name=zhangsan&age=20
  • 参数获取需要借助系统模块url,url模块用来处理url地址
 1  const http = require('http');
 2  // 导入url系统模块 用于处理url地址
 3  const url = require('url');
 4  const app = http.createServer();
 5  app.on('request', (req, res) => {
 6      // 将url路径的各个部分解析出来并返回对象
 7      // true 代表将参数解析为对象格式
 8      let {query} = url.parse(req.url, true);
 9      console.log(query);
10  });
11  app.listen(3000);

5. POST请求参数

  • 参数被放置在请求体中进行传输
  • 获取POST参数需要使用data事件和end事件
  • 使用querystring系统模块将参数转换为对象模式
 1  // 导入系统模块querystring 用于将HTTP参数转换为对象格式
 2  const querystring = require('querystring');
 3  app.on('request', (req, res) => {
 4      let postData = '';
 5      // 监听参数传输事件
 6      req.on('data', (chunk) => postData += chunk;);
 7      // 监听参数传输完毕事件
 8      req.on('end', () => { 
 9          console.log(querystring.parse(postData)); 
10      }); 
11  });

6. 静态资源

服务器端不需要处理,可以直接响应给客户端的资源就是静态资源,例如css、javascript、image文件。

 

 1 // 创建服务器,并且读取静态资源
 2 const http = require('http');
 3 const url = require('url');
 4 const path = require('path');
 5 const app = http.createServer();
 6 const fs = require('fs');
 7 const mime = require('mime');
 8 
 9 app.on('request', (req, res) => {
10     let pathname = url.parse(req.url).pathname;
11     pathname = pathname == '/' ? '/default.html' : pathname;
12     // 将用户的请求路径转换为实际的服务器硬盘路径
13     let realPath = path.join(__dirname, 'public' + pathname);
14     let type = mime.getType(realPath);
15 
16     // 读取文件
17     fs.readFile(realPath, (error, result) => {
18         // 如果文件读取失败
19         if(error != null) {
20             res.writeHead(404, {
21                 'content-type': 'text/html;charset=utf8'
22             })
23             res.end('文件读取失败');
24             return;
25         }
26         res.writeHead(200, {
27             'content-type': type
28         })
29         res.end(result);
30     })
31 });
32 
33 app.listen(3000);
34 console.log('服务器启动成功')
原文地址:https://www.cnblogs.com/guwufeiyang/p/13231674.html