如何使用nodejs发出子HTTP请求

时间:2013-10-23 11:26:09

标签: node.js http curl httprequest

我想知道如何使用HTTP请求或一些带有nodejs的lib来进行第二次请求(第一次访问外部URL)。下面是我如何通过PHP和cURL解决我的问题,我在哪里访问主网址,我采取会话(cookie)来发出第二个请求

$app->get('/parada/:termo', function ($termo) use ($app) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://olhovivo.sptrans.com.br/');
    curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    $store = curl_exec ($ch);
    curl_setopt($ch, CURLOPT_URL, 'http://olhovivo.sptrans.com.br/v0/Parada/Buscar?termosBusca='.$termo);
    $content = curl_exec ($ch);
    echo $content;
    curl_close ($ch);
});

我没有代码,因为我看到的所有示例都是http.get发出请求并关闭连接。

var http = require('http');
var options = {
  host: 'example.com',
  port: 80,
  path: '/foo.html'
};

http.get(options, function(resp){
  resp.on('data', function(chunk){
    //new request??
  });
}).on("error", function(e){
  console.log("Got error: " + e.message);
});

我需要通过http.get导航,因为我需要捕获第一个网址的cookie才能验证第二个网址。使用PHP的cURL很简单,因为只需要关闭第一个连接来发出第二个请求(保留cookie)


我试图抓住第一个请求的cookie,然后我尝试在第二个请求中插入cookie第一个请求,但是没有运行

var http = require('http');

var options = {
    host: 'www.olhovivo.sptrans.com.br',
    port: 80
};

http.get(options, function(resp){

    var teste = resp.headers;
        teste = teste['set-cookie'][0].split('=');
        var cok = 'apiCredentials-v0='+teste[1].replace('; path', '');

  resp.on('data', function(chunk){
    //new request??
    var options2 = {
        host: 'www.olhovivo.sptrans.com.br',
        port: 80,
        "set-cookie": cok,
        path: '/v0/Parada/Buscar?termosBusca=Paulista'
    };
    http.get(options2, function(resp2){
      resp2.on('data', function(chunk2){
        //new request??
        http.createServer(function (req, res) {

            //set content header
            res.writeHead(200, {
                'content-type': 'application/json'
            });
            //write msg
            res.end(chunk2);
        }).listen(8080);

        console.log('Server running 0n 8080');
      });
    }).on("error", function(e){
      console.log("Got error: " + e.message);
    });
  });
}).on("error", function(e){
  console.log("Got error: " + e.message);
});

2 个答案:

答案 0 :(得分:2)

在以下示例中,我发出第一个请求以获取Cookie apiCredentials。 我将此cookie添加到第二个请求的标头中。第二个请求从提供者返回正确的数据(一个不错的JSON答案)。

var http = require("http");
var initialRequestOptions = {
    host : 'olhovivo.sptrans.com.br',
    port : 80,
    path : '/'
};
var secondRequestOptions = {
    host : 'olhovivo.sptrans.com.br',
    port : 80,
    path : '/v0/Parada/Buscar?termosBusca=Morato',
    headers : {
        // This cookie will be replaced by the one received on the previous request
        'Cookie' : 'apiCredentials=39D1DE24EB4A....'
    }
};
var firstRequest = http.request(initialRequestOptions, function(response) {
    var cookie = response.headers['set-cookie'];
    if (cookie) {
        cookie = (cookie + '').split(";")[0];
        secondRequestOptions.headers['Cookie'] = cookie;
    }
    var body = '';
    response.on('data', function(chunk) {
        body += chunk;
    });
    response.on('end', function() {
        var secondRequest = http.request(secondRequestOptions, function(responseNew) {
            var dataBody = '';
            responseNew.on('data', function(chunk) {
                dataBody += chunk;
            });
            responseNew.on('end', function() {
                console.log(dataBody);
            });
        });
        secondRequest.on('error', function(e) {
            console.log('problem with request: ' + e.message);
        });
        secondRequest.end();

    });
});
firstRequest.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});
firstRequest.end(); 

答案 1 :(得分:1)

我建议使用request模块。

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
  }
})