day02-请求响应原理及HTTP 协议

HTTP协议的概念

超文本传输协议(英文:HyperText Transfer Protocol,缩写:HTTP)规定了如何从网站服务器传输超文本到本地浏览器,它基于客户端服务器架构工作,是客户端(用户)和服务器端(网站)请求和应答的标准。


image.png
报文

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


image.png
请求报文:
  • 1.请求方式 (Request Method):
    GET 请求数据
    POST 发送数据
  • 2.请求地址 (Request URL)
app.on('request', (req, res) => {
     req.headers  // 获取请求报文
     req.url      // 获取请求地址
     req.method   // 获取请求方法
 });
响应报文
    1. HTTP状态码:
      200 请求成功
      404 请求的资源没有被找到
      500 服务器端错误
      400 客户端请求有语法错误
    1. 内容类型
      text/html
      text/css
      application/javascript
      image/jpeg
      application/json
 app.on('request', (req, res) => {
     // 设置响应报文
     res.writeHead(200, {
         'Content-Type': 'text/html;charset=utf8‘
     });
 });
node创建服务器的方式
// 引用系统模块
 const http = require('http');
  // 创建web服务器
 const app = http.createServer();
  // 当客户端发送请求的时候
 app.on('request', (req, res) => {
        //  响应
       res.end('

hi, user

'); }); // 监听3000端口 app.listen(3000); console.log('服务器已启动,监听3000端口,请访问 localhost:3000')

HTTP请求与响应处理

1 请求参数

客户端向服务器端发送请求时,有时需要携带一些客户信息,客户信息需要通过请求参数的形式传递到服务器端,比如登录操作。

  • GET请求参数
    参数被放置在浏览器地址栏中,例如:http://localhost:3000/?name=zhangsan&age=20
    参数获取需要借助系统模块url,url模块用来处理url地址
const http = require('http');
 // 导入url系统模块 用于处理url地址
 const url = require('url');
 const app = http.createServer();
 app.on('request', (req, res) => {
     // 将url路径的各个部分解析出来并返回对象
         // true 代表将参数解析为对象格式
     let {query} = url.parse(req.url, true);
     console.log(query);
 });
 app.listen(3000);
  • 2POST请求参数
    参数被放置在请求体中进行传输
    获取POST参数需要使用data事件和end事件
    使用querystring系统模块将参数转换为对象格式
 // 导入系统模块querystring 用于将HTTP参数转换为对象格式
 const querystring = require('querystring');
 app.on('request', (req, res) => {
     let postData = '';
     // 监听参数传输事件
     req.on('data', (chunk) => postData += chunk;);
     // 监听参数传输完毕事件
     req.on('end', () => { 
         console.log(querystring.parse(postData)); 
     }); 
 });
路由

http://localhost:3000/index
http://localhost:3000/login
路由是指客户端请求地址与服务器端程序代码的对应关系。简单的说,就是请求什么响应什么。

image.png

// 1.引入系统模块http
// 2.创建网站服务器
// 3.为网站服务器对象添加请求事件
// 4.实现路由功能
//  1.获取客户端的请求方式
//  2.获取客户端的请求地址
const http = require('http');
const url = require('url');

const app = http.createServer();

app.on('request', (req, res) => {
    // 获取请求方式
    const method = req.method.toLowerCase();//转换成小写字母
    // 获取请求地址
    const pathname = url.parse(req.url).pathname;

     // 响应报文
    res.writeHead(200, {
        'content-type': 'text/html;charset=utf8'
    });

    if (method == 'get') {

        if (pathname == '/' || pathname == '/index') {
            res.end('欢迎来到首页')
        }else if (pathname == '/list') {
            res.end('欢迎来到列表页')
        }else {
            res.end('您访问的页面不存在')
        }

    }else if (method == 'post') {

    }

});

app.listen(8000);
console.log('服务器启动成功')
静态资源访问
const http = require('http');
const url = require('url');
const path = require('path');
// 读取文件
const fs = require('fs');
//获取文件的类型
const mime = require('mime');

const app = http.createServer();

app.on('request', (req, res) => {
    // // 获取用户的请求路径
    let pathname = url.parse(req.url).pathname;

     pathname = pathname == '/' ? '/default.html' : pathname;

    // 将用户的请求路径转换为实际的服务器硬盘路径
    let realPath = path.join(__dirname, '路径名称' + pathname);

     let type = mime.getType(realPath)
    // console.log(mime.getType(realPath))

    // 读取文件
    fs.readFile(realPath, (error, result) => {
        // 如果文件读取失败
        if (error != null) {
            res.writeHead(404, {
                'content-type': 'text/html;charset=utf8'
            })
            res.end('文件读取失败');
            return
        }
        res.writeHead(200, {
            'content-type': type
        })

        res.end(result);
    });
});

app.listen(3000);
console.log('服务器启动成功')

你可能感兴趣的:(day02-请求响应原理及HTTP 协议)