1.请求报文
①请求方式(Request Method)
GET 请求数据
POST发送数据
②请求地址
app.on('request' ,(req,res) =>{
req.headers //获取请求报文
req.url //获取请求地址
req.method //获取请求方法
});
2.响应报文
①HTTP状态码
200请求成功
404请求的资源没有找到
500 服务器端错误
400 客户端请求语法错误
②内容类型
text/html
text/css
application/javascript
image/jpeg
application/json
3.请求参数
客户端向服务器发送请求时,有时需要携带一些客户信息,客户信息需要通过请求参数的形式传递到服务器端,比如登陆
get请求参数
参数被放置在浏览器地址栏中,例如:http://localhost:3000/?name=zhangsan&age=20
POST请求参数
参数被放置在请求体中进行传输
获取POST参数需要使用data事件和end事件
使用querystring系统模块将参数转换为对象格式
//创建服务器模块
const http = require('http');
//app对象就是网站服务器对象
const app = http.createServer();
//处理请求参数模块
const queryString = require('querystring');
app.on('request',(req, res)=> {
//post参数时通过事件的方式接收的
//data当请求参数传递的时候触发data事件
//end 当参数传递完成时触发end事件
let postParams = {};
req.on('data',(params)=> postParams += params);
req.on('end',() => console.log(queryString.parse(postParams)));
res.end('ok');
});
app.listen(3000);
console.log('网站服务器已启动');
4.路由
路由是指客户端请求地址与服务器端程序代码对应关系,简单来说就是请求什么响应什么。
const http = require('http');
const app = http.createServer();
const url = require('url');
app.on('request',(req, res)=>{
// 获取请求方式
const method = req.method.toLowerCase();
// 获取请求地址
const pathname = url.parse(req.url).pathname;
//设置编码格式
res.writeHead(200,{
'content-type' : 'text/html;charset=utf8'
});
if(method == 'get'){
if(pathname == '/' || pathname == '/index'){
res.end('欢迎来到首页');
}else if (pathname == '/list') {
res.end('欢迎来到列表页');
}else {
res.end('您访问的页面不存在');
}
}else if(method == 'post'){
}
});
app.listen(3000);
console.log('服务器已经启动');
5.静态资源
服务端不需要处理,可以直接响应给客户端的资源就是静态资源,例如:CSS, Javascript, image文件
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const mime = require('mime');
const app = http.createServer();
app.on('request', (req, res) => {
//获取用户的请求路径
let pathname = url.parse(req.url).pathname;
pathname = pathname == '/' ? '/default.html' : pathname;
// __dirname + 'public' + pathname
//将用户的请求路径转换为服务器的实际硬盘路径
let realPath = path.join(__dirname, 'public' + pathname);
let type = mime.getType(realPath);
//读取文件
fs.readFile(realPath,(error,result)=>{
//如果文件读取失败
if(error != null){
res.writeHead(404,{
'content-type': 'text/html;charset=utf8'
})
res.end('文件读取失败');
return;
}
res.writeHead(200,{
'content-type' : type
})
res.end(result)
})
});
app.listen('3000');
console.log('服务器已经启动');
6.动态资源
相同的请求地址不同的响应资源,这种资源就是动态资源