简体   繁体   English

如何向第三方API写入Node.js请求?

[英]How do I write a Node.js request to 3rd party API?

Does anyone have an example of an API response being passed back from a http.request() made to a 3rd party back to my clientSever and written out to a clients browser? 有没有人有一个API响应的例子,从http.request()传递回第三方回到我的clientSever并写出到客户端浏览器?

I keep getting stuck in what I'm sure is simple logic. 我一直卡在我确定的简单逻辑中。 I'm using express from reading the docs it doesn't seem to supply an abstraction for this. 我正在使用快递阅读文档它似乎没有为此提供抽象。

Thanks 谢谢

Note that the answer here is a little out of date-- You'll get a deprecated warning. 请注意,这里的答案有点过时了 - 你会得到一个弃用的警告。 The 2013 equivalent might be: 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();
});

I would also recommend the request module if you're going to be writing a lot of these. 如果你要写很多这些,我也会推荐请求模块。 It'll save you a lot of keystrokes in the long run! 从长远来看,它会为你节省大量的击键!

Here is a quick example of accessing an external API in an express get function: 以下是在快速获取函数中访问外部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
});

Hope that helps! 希望有所帮助!

This example looks pretty similar to what you are trying to achieve (pure Node.js, no express): 这个例子看起来非常类似于你想要实现的东西(纯Node.js,没有表达):

http://blog.tredix.com/2011/03/partly-cloudy-nodejs-and-ifs.html http://blog.tredix.com/2011/03/partly-cloudy-nodejs-and-ifs.html

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM