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);
    }
});
相关推荐
AlanBruce4 小时前
摩尔信使MThings EdgeWeb HTTP API接口
网络·网络协议·http·上位机·plc·modbus·摩尔信使
ShineWinsu1 天前
对于Linux:HTTP中cookie、session的解析
linux·网络·c++·网络协议·http·cookie·session
减瓦1 天前
告别Postman——用VSCode优雅地发起Http请求
vscode·http·postman
wechatbot8881 天前
解决企业微信官方 API 短板:iPad 协议全功能对接方案
java·汇编·windows·http·微信·企业微信
Dxy12393102161 天前
Python 实现POST上行压缩上传可用HTTP库汇总
开发语言·python·http
午安~婉1 天前
git中http与ssh连接
git·http·ssh
Full Stack Developme1 天前
Tomcat 如何处理HTTP请求
java·http·tomcat
味悲1 天前
Apache HTTP 服务器配置
服务器·http·apache
q567315232 天前
Scrapy 框架集成稳定 HTTP 代理:中间件配置与断线重试实战
爬虫·网络协议·scrapy·http·中间件·http代理
完美火龙篇 四月的友2 天前
SpringBoot 即时聊天 IM 完整实现(HTTP会话管理 \+ WebSocket实时推送 \+ 离线消息)
spring boot·websocket·http