前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HTTP请求与响应处理

HTTP请求与响应处理

作者头像
清出于兰
发布2020-10-29 10:52:15
8960
发布2020-10-29 10:52:15
举报
文章被收录于专栏:前端学习笔记前端学习笔记

1. 请求参数

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

2. GET请求参数

参数被放置在浏览器地址栏中,例如: http://localhost:3000/?name=zhangsan&lage=20

代码语言:javascript
复制
 const http = require('http');
 // 导入url系统模块 用于处理url地址
 const url = require('url');
 const app = http.createServer();
 app.on('request', (req, res) => {
     // url.parse 将url路径的各个部分解析出来并返回对象
     // true 代表将参数解析为对象格式
     let {query} = url.parse(req.url, true);
     console.log(query);
 });
 app.listen(3000);
​
代码语言:javascript
复制
// 引用系统模块http
const http = require('http');
// 导入url系统模块 用于处理url地址
const url = require('url');
//app就是创建的web服务器对象
const app = http.createServer();
// 为网站服务器对象添加请求事件,当客户端有请求的时候就执行事件处理函数
// request事件名称,(req, res)=>{}事件处理函数
app.on('request', (req, res) => {
    // 获取请求地址 req.url
    // 设置响应报文
    // text/plain默认状态,纯文本  charset=utf-8编码格式
    res.writeHead(200, {
        'content-type': 'text/html;charset=utf-8'
    });
    console.log(req.url);
    // url.parse第一个参数:要解析的参数地址。第二个参数true:将查询参数解析成对象形式
    // console.log(url.parse(req.url, true));
    /* let params = url.parse(req.url, true).query;
    // 获取参数值
    console.log(params.name);
    console.log(params.age); */
​
    // 解构函数获取参数对象
    let {
        query,
        pathname
    } = url.parse(req.url, true);
    // 获取参数值
    console.log(query.name);
    console.log(query.age);
​
    if (pathname == '/index' || pathname == '/') {
        res.end('<h2>欢迎来到首页</h2>');
    } else if (pathname == '/list') {
        res.end('welcome to listpage');
    } else {
        res.end('no page');
    }
});
// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');

3. POST请求参数

  • 参数被放置在请求体中进行传输
  • 获取POST参数需要使用data事件和end事件
  • 使用querystring系统模块将参数转换为对象格式
代码语言:javascript
复制
// 引用系统模块http
const http = require('http');
//  // 导入系统模块querystring 用于将HTTP参数转换为对象格式
const querystring = require('querystring');
//app就是创建的web服务器对象
const app = http.createServer();
// 为网站服务器对象添加请求事件,当客户端有请求的时候就执行事件处理函数
// request事件名称,(req, res)=>{}事件处理函数
app.on('request', (req, res) => {
    // post参数是通过事件的方式接收的,不是一次触发的
    // data当请求参数传递的时候触发
    // end 当参数传递完成的时候触发
    // 由于post参数不是一次性接收完的,所以需要声明一个变量,触发data事件时把当前传递过来的参数和变量进行拼接,触发end事件时把拼接完成的参数进行输出
​
    let postParams = '';
    // 监听参数传输事件
    req.on('data', params => {
        postParams += params;
    });
    // 监听参数传输完毕事件
    req.on('end', () => {
        // querystring.parse()方法,能把字符串转换成对象模式
        console.log(querystring.parse(postParams));
        // console.log(postParams);
    });
    // 对于客户端发出的每一次请求,服务端都要做出响应 否则客户端将处于等待状态
    res.end('ok');
});
// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');

4. 路由

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

代码语言:javascript
复制
// 1. 引入系统模块http
const http = require('http');
// 引入系统url模块
const url = require('url');
// 2. 创建网站服务器
const app = http.createServer();
// 3. 为网站服务器对象添加请求事件
app.on('request', (req, res) => {
    // 4. 实现路由功能
    // (1).获取客户端请求方式
    const method = req.method.toLowerCase(); //toLowerCase()转换为小写
    // (2)获取请求地址
    const pathname = url.parse(req.url).pathname;
    // 处理响应报文
    res.writeHead(200, {
        'content-type': 'text/html;charset=utf8'
    });
    if (method == 'get') {
        if (pathname == '/index' || pathname == '/') {
            res.end('欢迎来到首页');
        } else if (pathname == '/list') {
            res.end('欢迎来到列表页');
        } else {
            res.end('您访问的页面不存在');
        }
    }
});
// 监听端口
app.listen(3000)
console.log('网站服务器已经成功启动');

5. 静态资源

服务器端不需要处理,可以直接响应给客户端的资源就是静态资源,例如CSS、JavaScript、 image文件。 如:http://ww.itcast.cn/images/logo.png

6. 动态资源

相同的请求地址不同的响应资源,这种资源就是动态资源。 http://www.itcast.cn/article?id=1 http://www.itcast.cn/article?id=2

代码语言:javascript
复制
// 1.引入系统 模块http
const http = require('http');
// 引入url模块
const url = require('url');
// 引入path模块
const path = require('path');
// 引入系统文件模块fs
const fs = require('fs');
const mime = require('mime');
// 2.创建网站服务器对象
const app = http.createServer();
// 3.为网站服务器对象添加请求事件
app.on('request', (req, res) => {
​
    // 获取用户请求路径
    let pathname = url.parse(req.url).pathname;
    pathname = pathname == '/' ? '/index.html' : pathname;
    //   __dirname 获取绝对路径
    // __dirname + 'public' + pathname;
    // path.join能拼接路径分隔符
    // 将用户的请求路径转换成实际的服务器硬盘路径
    let realPath = path.join(__dirname, 'public', pathname);
    // mime.getType(),让系统自动获取路径下的文本格式
    let type = mime.getType(realPath);
    // 读取文件
    fs.readFile(realPath, 'utf-8', (error, result) => {
​
        // 如果文件读取失败
        if (error != null) {
            res.writeHead(404, {
                'content-type': 'type;charset=UTF-8'
            });
            res.end('文件读取失败');
            return;
        }
        // 读取成功直接响应页面
​
        res.writeHead(200, {
            'content-type': type
        });
        res.end(result);
    });
});
// 4.监听事件
app.listen(3000);
console.log('网站服务器成功启动');

7. 客户端请求途径

  1. GET方式
  • 浏览器地址栏
  • link标签的href属性
  • script标签的src属性
  • img标签的src属性
  • Form表单提交
  1. POST方式
  • Form表单提交

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-10-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 请求参数
  • 2. GET请求参数
  • 3. POST请求参数
  • 4. 路由
  • 5. 静态资源
  • 6. 动态资源
  • 7. 客户端请求途径
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档