• 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请求

  • 相关阅读:
    -/bin/sh: ./led: not found的解决办法
    s5pv210启动debian出错提示bash: cannot set terminal process group (-1): Inappropriate ioctl for device
    s5pv210 cpu运行debian
    解决qt程序运行时的cannot create Qt for Embedded Linux data directory: /tmp/qtembedded-0出错情形
    easyui datagrid的API
    <% 拼写页面
    easyui编辑editor
    H2数据库介绍
    easyUI的datagrid控件日期列格式化
    oracle取出所有表和视图
  • 原文地址:https://www.cnblogs.com/BlingSun/p/7809220.html
Copyright © 2020-2023  润新知