如何使用node.js发出子HTTP请求 [英] how to make sub HTTP request using nodejs

查看:47
本文介绍了如何使用node.js发出子HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用HTTP请求或带有Node.js的某些lib发出第二个请求,以享受第一个请求(外部URL)的会话.以下是我如何使用PHP和cURL解决问题的方法,该在哪里访问主URL并使用会话(cookie)进行第二次请求

I wonder how I make a second request enjoying the session of the first requsição (of an external url) using the HTTP request or some lib with nodejs. below is how I solved my problem with PHP and cURL, where do I access the main url and I take the session (cookie) to make a second request

$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的示例都进行了请购并关闭了连接.


I have no code because all the examples I've seen of http.get making an requisition and closes the connect.

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)

I need to navigate via http.get, because I need to capture the cookie of the first url to be able to authenticate the second url. cURL with PHP is simple , because just need not close the first connection to make the second request(keeps cookies)

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

I tried to catch cookie the first request, then i tried to insert cookie the first request in the second request, but not run

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);
});

推荐答案

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

In the following example, I issue a first request just to get the cookie apiCredentials. The I add this cookie to the headers of the second request. The second request return the right data from the provider (a nice JSON answer).

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(); 

这篇关于如何使用node.js发出子HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆