请求参数
1.GET请求参数
- 参数被放置在浏览器地址栏中,例如:http://localhost:3000/?name =zhangsan&age=20
// 用于创建网站服务器的模块
const http = require('http');
// app对象就是网站服务器对象
const app = http.createServer();
// 用于处理url地址
const url = require('url');
// 当用户端有请求来的时候
// req请求对象,包含了请求相关的信息,
// 获取请求方式
app.on('request',(req,res) => {
// res.end 结束请求并且为客户端响应内容
// console.log(req.method);
// console.log(req.url);
// console.log(req.headers['accept']);
// 书写响应报文
res.writeHead(200,{
'content-type':'text/html;charset = utf8'
})
console.log(req.url);
// 要解析的url地址
// 要查询参数解析成对象形式
// url.parse(req.url,true)是把url字符串类型转化为对象类型
let {query, pathname } = url.parse(req.url,true);
// console.log(url.parse(req.url,true).query);
console.log(query.name)
console.log(query.age)
if( pathname == '/index' || pathname == '/'){
res.end('<h2>welcome to homepage</h2>');
}else if( pathname == '/list'){
res.end('<h2>Welcome to listpage</h2>');
}else{
res.end('<h2>not found</h2>');
}
if (req.method == 'POST'){
res.end('POST')
}else if(req.method == 'GET'){
res.end('get')
}
// res.end('<h2>hello user</h2>');
});
// 监听端口
app.listen(3000);
console.log("网站服务器启动成功")
2.POST请求参数
- 参数被放置在请求体中进行传输
- 获取POST参数需要使用data事件和end事件
- 获取GET参数使用req.url就可以了
- 使用querystring系统模块将参数转换为对象格式
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- method: 指定当前表单提交的方式值可以是get也可以是post -->
<!-- 如果不写post那默认就是get请求 -->
<!-- action:指定当前表单提交的地址 -->
<form method="post" action = "http://localhost:3000 ">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
post.js
// 用于创建网站服务器的模块
const http = require('http');
// app 对象就是网站服务器对象
const app = http.createServer();
// 处理请求参数模块
// 导入系统模块querystring用于将HTTP参数转换为对象格式
const querystring = require('querystring');
// 当客户端有请求来的时候
app.on('request',(req,res) =>{
// post参数是通过事件方式接受的
// data 当请求参数传递的时候触发data事件
// 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('网站服务器启动成功');