http(https) 的response和get请求

get请求:

var http=require('http');
var querystring = require('querystring');


options='http://baidu.com+参数’; 或者 options={ host:'', path:'', port:'', method:'', headers:{ 'conyent-type':'', 'content-Length':'',对于post请求必须 } } var result=''; varreq=http.get(options,function(res){ res.on('data',function(data){ result+=data; //此处的data是数据流 }) res.on('end',function(){ console.log(result); //此处是正常格式数据 }) }) 对于get请求,请求结束后会自动调用req.end()方法。

request请求

request请求

var http=require('http');
var querystring = require('querystring');


options='http://baidu.com+参数’;
或者
options={
   host:'', 必须
   path:'', 必须
   port:'',
   method:'',必须
   headers:{
   'conyent-type':'',
  'content-Length':'',对于post请求必须
    }
  }
var postData=querystring.stringify({        
        image:'base64Img'
    });
var result='';
varreq=http.get(options,function(res){

    res.on('data',function(data){
       result+=data;  //此处的data是数据流
   })
   res.on('end',function(){
      console.log(result);  //此处是正常格式数据
   })

})
req.on('error', function(e) {
          console.error(e);
     });
    req.write(postData);  发送请求参数

        req.end(function(){
         console.log('2end');
     });

)

一次请求执行过程:

首先发送请求,对于post请求然后要发送数据。请求结束后调用end方法。end()方法结束后调用请求中的回调函数。至此,res.on监听返回的数据,数据返回结束后出发on('end')事件。

request请求示例:


var http=require('http');
var querystring = require('querystring');


var
postData=querystring.stringify({ image:'base64Img' }); var option={ host:'localhost', path:'/hi', port:'3000', method:'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData)或 postData.length } }; var req2=http.request(option,function(res) { res.on('data', function(d) { process.stdout.write(d); }); res.on('end',function(){ console.log('接收完毕'); }); }); req.on('error', function(e) { console.error(e); }); req.write(postData); req.end(function(){ console.log('2end'); });

 host不要加http://,要看清是http请求还是https请求

posted @ 2017-11-09 14:29  申小贺  阅读(864)  评论(0编辑  收藏  举报