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);
    }
});
相关推荐
SemiTris1 小时前
Web 前端底层起源:HTML/CSS/JS、浏览器与 HTTP 完整脉络
http·html
修仙之路1 小时前
2.1 HTTP 协议核心:请求响应模型、状态码、Header 与 RESTful 设计
网络协议·http
程序员韩星3 天前
OpenAI 兼容接口返回 404,先查请求地址,再查模型名
前端·人工智能·http
我不会插花弄玉6 天前
5.应⽤层协议HTTP【由浅入深-网络】
http
如夏倾城7 天前
QUIC——HTTP/3 的唯一底层传输协议 及 0-RTT恢复
网络·网络协议·tcp/ip·安全·http
Thanks_ks8 天前
HTTPS:浏览器地址栏那把锁的工作原理
http·网络安全·https·tls·加密算法·数字证书·中间人攻击
杨凯凡8 天前
Spring Boot 大文件下载如何实现断点续传?HTTP Range、206 与 416 实战
spring boot·后端·http
FungLeo9 天前
成为全栈·Vue 管理后台篇·用 fetch 建一层可控的请求内核
前端·javascript·vue.js·http·fetch·formdata·接口封装
wuyk5559 天前
Spider-第03讲-HTTP速通与读懂响应
网络·爬虫·网络协议·http
杨凯凡10 天前
Spring Framework 7 HTTP Interface 实战:声明式 RestClient、超时与测试
java·spring·http