const http = require("http");
const querystring= require('querystring'); http.createServer(function(req,res){
//post —— req
// POST很大,会分段发送,分段接收
// data - 有一段数据到达触发(多次)
// end - 数据全部到达触发(一次) var str = ''; //存放数据
req.on('data',function(data){
console.log("接收data一次");
str+=data;
}); req.on('end',function(){
// console.log(str); //userName=aaa&pass=fdsalfjdsl&content=lsafjdla70455
var postData = querystring.parse(str);
console.log(postData); // { userName: 'fsadsafd', pass: 'adsfsafdsa', content: 'fasdfasfzxvxcbvasgasdgsad' }
}); res.end(); }).listen(8081)

案例:post和get

const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const urlLib = require('url'); var server = http.createServer(function(req,res){
//GET数据
var obj = urlLib.parse(req.url,true);
var url = obj.pathname;
const GET = obj.query; // POST数据
var str = '';
req.on('data',function(data){
str+=data;
}); req.on('end',function(){
const POST = querystring.parse(str);
/*
url - 要什么
GET - get数据
POST - post数据
*/
console.log(url,GET,POST);
// 当为post请求时,GET为空 /aaa {} { userName: 'post', pass: 'daf', content: 's' }
// 当为get请求时,POST为空 /aaa { userName: 'afdaf', pass: 'dafsaf', content: 'adsf' } {}
}); //文件请求
var file_name = "section05/www"+ url;
fs.readFile(file_name,function(err,data){
console.log('文件'+file_name);
if(err){
res.write('404')
}else{
res.write(data)
};
res.end();
}) }).listen(8081);
05-11 20:07