构建Web服务器
文章目录
一、HPPT信息
(1) 通用头信息(General)
- Request URL 请求的URL,向服务器端获取的内容
- Request Method 请求的方法,GET或POST
- Status Code 响应的状态码
- Remote Address 请求服务器的IP地址和端口号
状态码 分类:
200系列 : 服务器成功响应
300系列 : 响应的重定向, 跳转另一个URL
400系列 : 客户端错误
500系列 : 服务器错误
(2) 响应头信息(Response Headers)
- Connection 连接方式
- Content-Type 响应文件类型
- Transfer-Encoding 响应时的传输方式
(3) 请求头信息(Request Headers)
- Accpet 客户端接受的文件类型汇总
- Connection 客户端和服务器端的连接方式
- User-Agent 客户端使用的浏览器
二、HTTP模块
可模拟浏览器向服务器端发送请求,也可创建Web服务器
(1) 模拟浏览器
const http = require('http');
http.get('http://www.baidu.com/index.html',(res)=>{
//res:响应的对象
console.log(res.statusCode);//打印状态码
//获取服务器端响应的数据
res.on('deat',(buf)=>{
//on('data'(buf)=>{}):当有数据传递时触发函数,buf接收响应数据
consol.log(buf);
});
});
(2) 创建Web服务器
const http = require('http');
//创建web服务器
var server = http.createServer();
//分配端口,监听端口
server.listen(3000,()=>{
console.log("Web服务器创建成功!");
});
server.on('request',(req,qes)=>{
//request,请求信息
//req,请求的对象
//res,响应的对象
console.log(req.url);
//设置响应内容
res.writeHead(302,{
Location:'http://www.baidu.com'
});
//响应结束
res.end();
});