关于express模块下request.on方法的详细说明
一般用于post请求,获取参数
request.on()方法是用于监听 HTTP 请求事件
request.on('data', fn)用来获取消息体
request.on('end', fn) 用来拼接消息体
app.post("/info",(request,response)=>{
let body = '';
request.on("data",thunk=>{
body += thunk;
})
request.on("end",()=>{
/*
*querystring.parse(str, 分隔符, 赋值符,
*可接受字符串的最大长度,默认为1000),将字符串转成对象
*/
console.log(querystring.parse(body));
response.json({
ok: 1,
msg: "post->info"
})
})
})
上述代码主要是通过post方式发送请求,使用request.on方法获取到消息体数据,并将消息体数据拼接至字符串中,最后将字符串通过querystring方法转换为对象,并输出。
简单来说,通过post方式,得到是消息体数据,从而操作消息体数据,而get方式,获取的是路由中的参数数据,可操作的则是路由中的参数。