实现POST服务器

//post请求的基本服务器
var http=require("http");
var jsonData="";
http.createServer((req,res)=>{
    console.log(req);
    req.on("data",(chunk)=>{
        jsonData+=chunk;
    });
    req.on("end",()=>{
        console.log("???");
        console.log(jsonData);
        var reqObj=JSON.parse(jsonData);
        console.log(reqObj);
        var resObj={
            message:"hello "+reqObj.name,
            question:"Are you "+reqObj.age+" age ?"
        };
        res.writeHead(200);
        res.end(JSON.stringify(resObj));
   });
    console.log("??");
}).listen(8080);
console.log("???");

var options={
    host:"127.0.0.1",
    path:"/",
    port:"8080",
    method:"POST"
};
var req=http.request(options,(response)=>{
    console.log("????");
    var responseData="";
    response.on("data",(chunk)=>{
        responseData+=chunk;
    });
    response.on("end",()=>{
        var dataObj=JSON.parse(responseData);
        console.log("Raw Response : "+responseData);
        console.log("Message : "+dataObj.message);
        console.log("Question : "+dataObj.question);
    });
    console.log("?????");
});
req.write('{"name":"Soul","age":21}');
req.end();
console.log("????????");

   

代码初次执行结果(注意代码的执行顺序):

 

浏览器发出请求后的结果(注意代码执行的内容):

 ===> 

 

posted @ 2016-07-04 20:52  DeadGhost  阅读(1106)  评论(0编辑  收藏  举报