61 # http 数据处理

node 中的核心模块 http 可以快速的创建一个 web 服务

javascript 复制代码
const http = require("http");
const url = require("url");

// req => request 客户端的所有信息
// res => respone 可以给客户端写入数据
const server = http.createServer();

server.on("request", (req, res) => {
    // 请求的方法
    console.log(req.method); // 方法名是大写的
    console.log(req.url); // 请求路径
    // http://localhost:3001/?a=1&b=2#333
    let { pathname, query } = url.parse(req.url, true);
    console.log(pathname); // 路径
    console.log(query); // 查询参数

    // request 是一个可读流
    // 有请求体才会触发 data 事件 curl -v -X POST --data k=1 http://localhost:3001
    let arr = [];
    req.on("data", (chunk) => {
        arr.push(chunk);
        console.log("chunk---->", chunk.toString());
    });
    // 请求发送过来之后,一定会触发  end 事件
    req.on("end", () => {
        console.log("req.end---->", Buffer.concat(arr).toString());
    });

    console.log(req.httpVersion); // http 版本
    // 所有的 header 获取时都是小写
    console.log(req.headers);

    // 可写流 write end 可写流的方法
    res.statusCode = "222";
    res.statusMessage = "kaimo666";
    // 设置响应头
    res.setHeader("kaimo", "313");
    res.setHeader("Content-type", "text/html;charset=utf-8");
    res.write("hello world");
    res.end("凯小默的博客");
    // 不能下面这样写,会报错 `write after end`,它表示文件已经关闭但是又进行了写入操作
    // res.end("凯小默的博客");
    // res.write("hello world");
});

// curl -v http://localhost:3000
let port = 3000;
// listen 是一个订阅模式,等会开启后会触发对应的回调的方法
server.listen(port, () => {
    console.log("serve run", port);
});

使用 curl 请求

bash 复制代码
curl -v -X POST --data k=1 http://localhost:3001

访问 http://localhost:3001/?a=1&b=2#333

nodemon

实现文件变化后自动重启 nodemon (node monitor) 可以监视自动重启

bash 复制代码
npm install nodemon -g
nodemon "61 # http 数据处理.js"

node 中基本上所有的模块都继承于 eventEmitter,实现端口号被占用可以自动重启 Error: listen EADDRINUSE: address already in use :::3000

javascript 复制代码
server.on("error", (err) => {
    console.log("err---->", err);
    // 如果端口号被占用自动重启
    if (err.code === "EADDRINUSE") {
        server.listen(++port);
    }
});
相关推荐
esmember15 小时前
电路研究9.2.6——合宙Air780EP中HTTP——HTTP GET 相关命令使用方法研究
网络·网络协议·http·at指令
霸王蟹21 小时前
http和https的区别?
网络·笔记·网络协议·学习·http·https
精通HelloWorld!21 小时前
使用HttpClient和HttpRequest发送HTTP请求
java·spring boot·网络协议·spring·http
泪不是Web妳而流1 天前
BurpSuite抓包与HTTP基础
网络·经验分享·网络协议·安全·http·网络安全·学习方法
zhuyasen1 天前
多维度详细比较 kratos、go-zero、goframe、sponge 框架
后端·http·微服务·rpc·golang
ybq195133454311 天前
javaEE-6.网络原理-http
网络·网络协议·http
我的青春不太冷1 天前
《深入理解HTTP交互与数据监控:完整流程与优化实践》
网络·经验分享·科技·网络协议·学习·http·架构
A.sir啊1 天前
爬虫基础(五)爬虫基本原理
网络·爬虫·python·网络协议·http·pycharm
高野4402 天前
【网络】3.HTTP(讲解HTTP协议和写HTTP服务)
网络·http·iphone
codkingo2 天前
CSRF 跨站请求伪造漏洞
web安全·http·网络安全·csrf