node.js实现HTTP GET/POST

2015-03-29  文晶 

原文地址:http://samwize.com/2013/08/31/simple-http-get-slash-post-request-in-node-dot-js/

频繁用到,频繁搞不明白,特此记录。通过request实现

get 请求 (http://127.0.0.1:8009/xxx/xxx/x?loginName=test)

var name = req.body.loginData

var headers = {
          'User-Agent':       'Super Agent/0.0.1',
          'Content-Type':     'application/x-www-form-urlencoded'
      }

// Configure the request
      var options = {
          url: 'http://127.0.0.1:8009/xxx/xxx/x',
          method: 'GET',
          headers: headers,
          qs: {'loginName': name}//多参数继续增加'XXX':XX
      }

// Start the request
      request(options, function (error, response, body) {
          if (!error && response.statusCode == 200) {
              // Print out the response body
              console.log(body);
              res.json(body);
          }
      })


post请求

var formData = querystring.stringify(req.body);

var headers ={
        'User-Agent':'Super Agent/0.01',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    var options = {
        url:'http://127.0.0.1:8009/xxx/xxx/x',
        method:'POST',
        headers:headers,
        form:formData
    }
    request(options,function(error,response,body){
        if(!error && response.statusCode == 200){
            console.log(response.headers);
            console.log("网页返回:"+body+"\n   ");
        }else{
            res.direct(response.headers.location);
        }
    })

482°/4794 人阅读/3 条评论 发表评论

文晶  2015-03-29

req.pipe(request.post('http://wwww.xxx.com/selfservice/xxx.action',{form:formData})).pipe(res);


文晶  2015-03-29

参考: http://floss.zoomquiet.io/data/20110920101930/index.html https://github.com/request/request http://zhidao.baidu.com/link?url=iO_JxeSv1dyClfe6_mHwuusnCCyEYcvvfTjEL308ZO9F5XJhpne5szonOffZExloUwcjB19AzTwlzXx1vWYrjK


熊志男  2015-04-03


登录 后发表评论