使用node创建静态服务器
# 0.前言
本篇博客是node-server案例的文档笔记,该项目的github仓库地址:https://github.com/wangjs-jacky/node-server (opens new window)
主要内容:
- 介绍了在学习
node阶段非常好用的三个node执行环境。 curl的基础使用。- 借助
@types/node快速学习api,如对request设置IncomingMessage类属性,可以使用ctril+.快速查找到request拥有的属性和方法。
# 1.工具介绍
# JavaScript 执行环境
以下工具不宜用于生产环境:
node-dev当文件更新时自动重启
node,避免每次改完代码都要重新运行。ts-node让
node支持直接运行TypeScript代码ts-node-dev同时结合上面两个工具,可以使用
TypeScript开发Node.js程序,且会自动重启。
# VSCode配置
Quick Fix默认快捷键:Ctrl+.- 如果是
windows电脑,可以在setting.json里面添加字段,目的是让VSCode调用cmder里的git和bash
# curl基础使用
# GET
curl -v http://localhost:8888
# POST
curl -v -d "name=wangjiasheng" http://localhost:8888
# 设置请求头
curl -H 'Content-Type:application/json'
# 设置动词
curl -X PUT
# JSON 请求
curl -d '{"name":"wangjiasheng"}' -H 'Content-Type:application/json' http://localhost:8888
# 更多参数
curl --help
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 2.创建步骤
npm init -y- 新建
index.ts文件 npm install -D @types/node安装node声明文件- 引入
http模块(VSCode使用ctrl+.自动导入) - 用
http创建server(createServer()) - 监听
server的request事件 server.listen(8888)开始监听8888端口- 使用
curl -v http://localhost:8888发请求
# 3.类
# http.Server类
✔️需要根据文档知道http.createServer()的返回值的类型
✔️了解server拥有几个事件和方法
目前只使用了
request事件和listen()方法。
✔️根据文档知道http.Server继承了net.Server类,并找到net.Server类拥有的事件和方法。
# (request,response)是什么类型?
✔️通过console.log(request.constructor)可以知道http.IncomingMessage的实例
✔️通过console.log(response.constructor)可以知道http.ServerResponse的实例
# 4.如何使用Node.js获取请求内容
在对request 和 response设置指定类后,无需查阅官网,也可以快速知道 变量 有什么属性和方法。
# get请求
server.on('request',(request:IncomingMessage,response:ServerResponse)=>{
const {method,url,header} = request
})
1
2
3
2
3
# post请求
curl -v -d "name=wangjiasheng" http://localhost:8888
1
Node.js
server.on('request',(request,response)=>{
request.on('data',fn) // 获取消息体
request.on('end',fn) // 拼接消息体
})
1
2
3
4
2
3
4
编辑 (opens new window)
上次更新: 2022/04/06, 15:04:00