创建一个http服务器
原生搭建服务器:
// 引入网络通信模块
const http = require('http');
// 创建一个服务器对象
const app = http.createServer()
// 声明端口号
const port = 1024
// 绑定request事件
app.on('request', (req, res)=>{
// req: 请求对象,客户端发送来的数据封装到该对象中
// res: 响应对象,服务器用于做出回应的对象
// 服务器向客户端写数据
res.write('hello\n')
// 结束响应并传递数据
res.end('world')
})
// 启动服务器
app.listen(port, () => {
// 当服务器启动成功后,就会调用此函数
console.log(`server start: http://127.0.0.1:${port}`)
})
静态资源服务器
原生搭建静态资源文件夹:
// 什么是静态资源?
// 不会发生变化的资源就是静态资源,静态资源一般指不会变化的文件
// 静态资源服务器?
// 用于访问静态资源的服务器
const http = require('http');
const path = require('path');
const fsp = require('fs/promises');
const app = http.createServer();
// 定义静态资源文件夹
const staticDirPath = path.join(__dirname, 'public')
app.on('request', (req, res) => {
// 拼接资源路径
let assetPath = path.join(staticDirPath, `.${req.url}`)
// 判断文件是否存在
fsp.stat(assetPath).then((stat) => {
// 判断当前路径是否是一个目录
if (stat.isDirectory()) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('无效文件')
return
}
// 读取文件
fsp.readFile(assetPath).then(data => {
// data: 读出来的文件数据
res.write(data)
}).finally(() => {
res.end()
})
}).catch(reason => {
console.error(reason)
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('404资源未找到')
})
})
app.listen(80, () => {
console.log('server start on: http://127.0.0.1')
})
express搭建服务器
使用node.js导入express库创建服务器
const express = require('express'); // 引入 express 模块
const app = express(); // 创建服务器应用程序对象
const port = 80
// 注册接口
// 接口: 网络接口,一个 url 路径,对应服务器上一个提供服务的功能,这个功能就是服务器上的一个接口
// 第一个参数: url
// 第二个参数: 接口回调
app.get('/greeting', (req, res) => {
res.end('hello world')
})
app.get('/', (req, res) => {
res.end('ok123')
})
// 启动服务器
app.listen(port, () => {
console.log(`server start on: http://127.0.0.1`)
})
http协议
初步了解http相关协议:
## http协议
#### 什么是http协议
http (Hypertext transfer protocol)全称 超文本传输协议
分析理解:
- 超文本:比文本更多的信息(图片,超链接,媒体资源等等)
- 传输:运送
- 协议:服务端客户端共同认可的规则
连起来理解:运送比文本更多信息的 “服务器客户端共同认可的” 规则
> 协议就像游戏规则,规定了服务器和客户端怎么互相聊天,怎么一起愉快的玩耍
#### 通过浏览器直观看看http协议
打开chrome浏览器,f12或ctrl+shift+i,在network下查看请求
#### 常用请求头和响应头
请求头就是浏览器上的 ```request header```
响应头就是浏览器上的 ```response header```
- ```Request Method```:请求方法
名称 | 特点 | 服务器取值方式
---|---|---
get | 传递参数在url上可见 | 通过```url.parse(req.url).query```取值
post | 传递参数在url上不可见 | 通过```req.body```取值
- ```Content-Type```:内容类型
有常见的以下几种类型
名称 | 含义
---|---
text/html | html文档
text/plain | 纯文本
image/jpeg | .jpg图片
image/png | .png图片
text/xml | xml文档
application/json | json数据
application/x-www-form-urlencoded | 表单url编码数据,例如:a=1&b=2&c=3
multipart/form-data | 上传文件时常看到
charset=utf-8 | 指定编码集
- ```Status Code```:状态码
状态码只指示请求或响应状态,不对业务负责
常见状态码
代码 | 含义
--- | ---
200 | 请求成功
302 | 资源重定向
304 | 资源未改变,使用浏览器缓存
400 | 客户端请求的语法错误,服务器无法理解
403 | 权限不足 限制访问
404 | 资源未找到
500 | 服务器内部错误
503 | 请求超时
- ```User-Agent```:访问代理
意思是什么东西访问了服务器,通常可以用作平台判断。例如:不同浏览器,该值不一样