Node.js中http模块获取请求参数
一、get方法请求参数
在get请求参数中参数一般放在浏览器地址中
例我们要获取http://127.0.0.1:3000/?name=ggboy&age=9中的名字和年龄信息
如果我们使用req.url来获取的话
server.on('request',(req,res)=>{
const url = req.url //获取请求的地址
console.log(url)
})
命令行工具的输出结果为:/?name=ggboy&age=9
很显然不是我们想要的结果
这时我们可以
// 引包 导入http包
const http = require('http');
// 创建服务器实例
const server = http.createServer();
//引入url包
const url = require('url');
// 发起请求
server.on('request',(req,res)=>{
//获取请求的地址
const path = url.parse(req.url,true).query
console.log(path)
console.log(path.name)
console.log(path.age)
})
//监听端口号为3000窗口
server.listen(3000,(err)=>{
if( !err ){
console.log('服务器已经开启 我们可以通过http://127.0.0.1:3000 来访问');
}
})
引入url包 首先要安装url模块,在全局环境下安装url模块
在cmd中输入命令 npm install url -g
使用url.parse()方法来解析url 第一个参数要解析的url,第二个参数将查询参数解析成对象的形式,它的返回值也是 一个对象。对象下的query中就有我们想要的数据。
二、post方法请求参数
psot请求参数没有在浏览器地址中,它一般是通过事件来接受的。我们通过表单提交时间来演示一下:
<form action="http://127.0.0.1:3000" method="post">
<input type="text" name="name" />
<input type="password" name="pwd" />
<input type="submit" value="按钮" />
</form>
当我们点击按钮请求参数我们可以在浏览器中的Form Data看到
接下来我们就可以来获取它了
// 引包 导入http包
const http = require('http');
// 创建服务器实例
const server = http.createServer();
//处理请求参数模块
const querystring = require('querystring');
// 发起请求
server.on('request',(req,res)=>{
// 当请求参数传递时触发data事件
// 当请求参数传递结束时触发end事件
let postParams = ''
req.on('data',(parmas)=>{
postParams += parmas
})
// parmas 为请求传递过来的参数
req.on('end',()=>{
//通过querystring的parse方法把参数转成对象
const parmasObj=querystring.parse(postParams)
console.log(parmasObj);
})
})
//监听端口号为3000窗口
server.listen(3000,(err)=>{
if( !err ){
console.log('服务器已经开启 我们可以通过http://127.0.0.1:3000 来访问');
}
})
注意:post请求参数有时候会很长,需要分段进行接收
在命令行窗口输出的结果为:
[Object: null prototype] { name: 'zhangsan', pwd: '123456' }
我们可以在通过parmasObj,name和parmasObj.pwd来获取请求的数据。