【问题标题】:how to make sub HTTP request using nodejs如何使用nodejs发出子HTTP请求
【发布时间】:2013-11-01 15:35:57
【问题描述】:

我想知道如何使用 HTTP 请求或带有 nodejs 的某个库来享受第一个请求(外部 url)的会话的第二个请求。下面是我如何解决我的 PHP 和 cURL 问题,我在哪里访问主 url,我使用会话(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 导航,因为我需要捕获第一个 url 的 cookie 才能验证第二个 url。使用 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);
});

【问题讨论】:

  • 您是否编写了任何示例 nodejs 代码但无法正常工作,或者您只想为您编写它?

标签: node.js http curl httprequest


【解决方案1】:

在以下示例中,我发出第一个请求只是为了获取 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(); 

【讨论】:

    【解决方案2】:

    我建议使用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.
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 2015-04-21
      • 2019-10-20
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 2018-05-04
      • 2023-03-07
      相关资源
      最近更新 更多