HTTP协议的概念:
它是超文本传输协议,规定了如何从网站服务器传输超文本到本地浏览器,是客户端和服务器请求和应答的标准
报文:
在HTTP请求和响应的过程中传递的数据库就叫报文,包括要传送的数据和一些附加信息,并且要遵守规定好的格式。
请求报文:
客户端向服务器端发送请求的数据
响应报文:
服务器端接收到请求报文时,对客户端的响应数据
在浏览器的开发者工具的NetWork中,Request Headers就是请求报文,Response Headers就是响应报文
请求方式:
get :
请求数据(请求地址URL,超链接a,重定向等都是get请求方式)
post 发送数据:(用于发送一些重要的数据,例如账号,密码等,使用form中的method中可以选择post请求方式)
使用req.method可以判断请求方式
web.js
//引用系统模块
const http = require('http');
//创建web服务器
const app = http.createServer();
//当客户端发送请求的时候
app.on('request',(req,res)=>{
console.log(req.method);
//req为请求对象,res为响应对象(给浏览器返回一个数据)
res.end('hello world');
});
//监听3000端口
app.listen(3000);
console.log('创建服务器成功,请访问localhost:3000');
web.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>测试</title>
</head>
<body>
<form action="http://localhost:3000" method="post">
<input type="submit">
</form>
</body>
</html>
使用node 执行web.js文件
用浏览器输入localhost:3000,命令行工具输出请求方式为get
点击表单,有post请求输出,post请求执行后,表单会发生一个默认行为,跳转到action的输入地址,请求方式为get
根据不同的请求地址响应不同的内容
//引用系统模块
const http = require('http');
//创建web服务器
const app = http.createServer();
//当客户端发送请求的时候
app.on('request',(req,res)=>{
if(req.method=='POST'){
res.end('post');
}else if(req.method=='GET'){
res.end('get');
}
});
//监听3000端口
app.listen(3000);
req.url:请求地址
req.url可以获得localhost:3000后面的请求地址,输入localhost:3000时req.url为"/",输入localhost:3000/index时,req.url为"/index",可以根据不同的请求地址来响应不同的内容
app.on('request',(req,res)=>{
if(req.url=='/index'){
res.end('index');
}else if(req.murl=='/login'){
res.end('login');
}
req.headers:获取请求报文,它是通过键值对保存的一个数组,要获取具体的信息可以使用req.headers[键]获得
响应报文
res.writeHead(500,{
'content-type':'text/plain;charset=utf8'
});
//为服务器写入一个500的状态码,和设置文本的类型设置字符集
//获取get请求参数
const url = require('url');
//该模块可以用于处理url地址
//let pathname=url.parse(req.url,true).pathname;
let {query,pathname}=url.parse(req.url,true);
//解构出请求参数和请求路径
//1.要解析的url地址 2.将查询参数解析成对象形式
//query里面是参数的数组,用query.属性的方式来获取
post请求方式
method:指定当前表单提交的方式
action:指定当前表单提交的地址
//处理请求参数模块
const querystring = require('querystring');
<form method="post" action="http://localhost:3000">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
//当客户端有请求来的时候,on用来绑定事件
app.on('request',(req,res)=>{
//post参数是通过事件的方式接受的
//data当请求参数传递的时候触发data事件
//end当参数传递完成的时候触发end事件
let postParams = '';
req.on('data',params => {
postParams += params;
//拼接请求参数
});
req.on('end',()=>{
//把字符串转化为对象形式
let a = querystring.parse(postParams);
console.log(a);
});
});