1

我想知道如何使用 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);
});
4

3 回答 3

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(); 
于 2014-03-20T22:54:30.680 回答
1

我建议使用请求模块。

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.
  }
})
于 2016-04-22T11:00:24.617 回答
0
Use the sub request npm module

// You can use whatever HTTP library you like.
const axios = require('axios');

const blueprint = [
  {
    requestId: 'req1',
    uri: 'https://gist.githubusercontent.com/e0ipso/7cafb6b7debe786cfb60f617fa89ba81/raw/a6590d3cc87d0c00485c9e428c8b7c29da21b704/foo-bar.json',
    action: 'view'
  },
  {
    requestId: 'req2',
    uri: 'https://gist.githubusercontent.com/e0ipso/7cafb6b7debe786cfb60f617fa89ba81/raw/a6590d3cc87d0c00485c9e428c8b7c29da21b704/the-end.json',
    action: 'view'
  },
  {
    requestId: 'req1.1',
    uri: "https://gist.githubusercontent.com/e0ipso/7cafb6b7debe786cfb60f617fa89ba81/raw/a6590d3cc87d0c00485c9e428c8b7c29da21b704/{{req1.body@$['my-key']}}.json",
    action: 'view',
    waitFor: ['req1']
  },
  {
    requestId: 'req1.1.1',
    uri: 'https://gist.githubusercontent.com/e0ipso/7cafb6b7debe786cfb60f617fa89ba81/raw/a6590d3cc87d0c00485c9e428c8b7c29da21b704/{{req1.1.body@$.akward[*]}}.json',
    action: 'view',
    waitFor: ['req1.1']
  }
];

// Assuming '/subrequests' is listening for subrequests calls.
axios.get('http://127.0.0.1:3456/subrequests', {
    params: {
      query: JSON.stringify(blueprint),
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });



https://www.npmjs.com/package/subrequests
于 2022-02-01T10:45:35.773 回答