搜索文档
定义
- HTTP:超文本传输协议。
- HTTP 是浏览器与服务器直接的协议。
- 浏览器 ---> 服务器:请求,产生请求报文
- 服务器 ---> 浏览器:响应,产生响应报文
请求报文
- 请求行
- 请求头
- 请求体
响应报文
响应行
200 - 成功
403 - 禁止请求
404 - 找不到资源
500 - 服务器内部错误
| 状态码 | 含义 | | :----: | :--------: | | 1xx | 信息响应 | | 2xx | 成功响应 | | 3xx | 重定向消息 | | 4xx | 客户端错误 | | 5xx | 服务端错误 |
响应头
响应体
创建 HTTP 服务
引入 http 模块
创建服务对象
配置端口
jsconst http = require('http'); // 创建服务对象 const server = http.createServer((req, res) => { // rt:请求报文 // re:响应报文 res.end('Hello'); }); // 配置端口,启动服务 server.listen(9000, () => { console.log('服务已启动……'); })注意事项
启动 HTTP 服务后,不支持热更新,需要重启服务。
响应内容中使用中文会乱码,可如下设置
jsconst server = http.createServer((req, res) => { res.setHeader('content-type', 'text/html;charset=utf-8') res.end('你好'); });若端口被占用程序跑不起来,会报错。可在资源监视器中查看端口占用情况。
提取 HTTP 报文
| 说明 | API |
|---|---|
| 获取请求方式 | res.method |
| 获取请求 URL | res.url |
| 获取 HTTP 协议版本号 | res.httpVersion |
| 获取请求头 | res.headers |
提取请求体中的参数
js
const http = require('http');
// 创建服务对象
const server = http.createServer((req, res) => {
let body = '';
// 绑定 data 事件
req.on('data', e => {
body += e;
});
// 绑定 end 事件
req.on('end', e => {
console.log(body);
res.end('Http')
})
});
// 配置端口,启动服务
server.listen(9000, () => {
console.log('服务已启动……');
})提取 URL 中的参数
方式一:不推荐
jsconst http = require('http'); const url = require('url'); // 创建服务对象 const server = http.createServer((req, res) => { let e = url.parse(req.url, true); let { account, password } = e.query; console.log(`账号:${account}`); console.log(`密码:${password}`); res.end('Hello'); }); // 配置端口,启动服务 server.listen(9000, () => { console.log('服务已启动……'); })方式二:推荐
jsconst http = require('http'); const url = require('url'); // 创建服务对象 const server = http.createServer((req, res) => { let url = new URL(req.url, 'http://127.0.0.1:9000'); console.log(`账号:${url.searchParams.get('account')}`); console.log(`密码:${url.searchParams.get('password')}`); res.end('Node'); }); // 配置端口,启动服务 server.listen(9000, () => { console.log('服务已启动……'); })
