var http = require('http');
http.createServer(function (request,response) {
var urlObj = url.parse(request.url,true); //将request 的 url 转为 js 对象,true表示将转成js对象默认false。false就是字符串
// 将不是小写的请求路径和method转为小写
request.url = request.url.toLowerCase();
request.method = request.method.toLowerCase();
//接下来是关键
if(urlObj.pathname === '/add'&& request.method ==='post'){ //post方式提交的方式 请求的pathname是 /add
//监听request 的对象的 data 事件 和 end 事件
//chunk(块)是本次提交的部分数据,是一个buffer对象
var arr = []; //保存用户每次提交的数据 // 也可以var str = '';
request.on('data',(chunk)=>{ // request.on('data',(chunk)=>{
arr.push(chunk); // str += chunk.toString('utf-8'); //string类型
}); // });
//触发后,表明所有数据提交完毕
request.on('end',()=>{
//1. 将arr东西汇总
var postBody = Buffer.concat(arr); //Buffer.concat(*arrs); js自带 concat将传入的多个buffer数组结合为一个buffer
//2. 将buffer对象转为字符串
postBody = postBody.toString('utf-8'); //title=aaaaa&url=bbbbb&text=ccccc
//3.把post请求查询的字符串转为js对象
postBody = querystring.parse(postBody); // { title: 'aaaaa', url: bbbbb', text: 'ccccc'}
//接下来就可以使用接收到的参数进行下一步工作
}
}).listen(8080,function(){
console.log('http://localhost:8080');
})
node.js 处理post请求,不使用express
猜你喜欢
转载自blog.csdn.net/qq_38340601/article/details/81381167
今日推荐
周排行