Подтвердить что ты не робот

Как написать запрос Node.js стороннему API?

Есть ли у кого-нибудь пример ответа API, который передается обратно от http.request(), сделанного третьей стороне обратно на мой клиент, и записывается в браузер клиентов?

Я все время зацикливаюсь на том, что я уверен в простой логике. Я использую выражение от чтения документов, это, похоже, не дает абстракции для этого.

Спасибо

4b9b3361

Ответ 1

Обратите внимание, что ответ здесь немного устарел. Вы получите устаревшее предупреждение. В эквиваленте 2013 года может быть:

app.get('/log/goal', function(req, res){
  var options = {
    host : 'www.example.com',
    path : '/api/action/param1/value1/param2/value2',
    port : 80,
    method : 'GET'
  }

  var request = http.request(options, function(response){
    var body = ""
    response.on('data', function(data) {
      body += data;
    });
    response.on('end', function() {
      res.send(JSON.parse(body));
    });
  });
  request.on('error', function(e) {
    console.log('Problem with request: ' + e.message);
  });
  request.end();
});

Я бы также рекомендовал модуль request, если вы собираетесь писать много из них. Это сэкономит вам много нажатий клавиш в долгосрочной перспективе!

Ответ 2

Вот краткий пример доступа к внешнему API в функции экспресс-получения:

app.get('/log/goal', function(req, res){
    //Setup your client
    var client = http.createClient(80, 'http://[put the base url to the api here]');
    //Setup the request by passing the parameters in the URL (REST API)
    var request = client.request('GET', '/api/action/param1/value1/param2/value2', {"host":"[put base url here again]"});


    request.addListener("response", function(response) { //Add listener to watch for the response
        var body = "";
        response.addListener("data", function(data) { //Add listener for the actual data
            body += data; //Append all data coming from api to the body variable
        });

        response.addListener("end", function() { //When the response ends, do what you will with the data
            var response = JSON.parse(body); //In this example, I am parsing a JSON response
        });
    });
    request.end();
    res.send(response); //Print the response to the screen
});

Надеюсь, что это поможет!