如何从Node.js或Express.js中发出HTTP请求?我需要连接到另一个服务。我希望调用是异步的,并且回调包含远程服务器的响应。


当前回答

你也可以使用Requestify,这是我为nodeJS +编写的一个非常酷且非常简单的HTTP客户端,它支持缓存。

只需对GET方法请求执行以下操作:

var requestify = require('requestify');

requestify.get('http://example.com/api/resource')
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);

其他回答

如果你需要向一个IP和一个域发送GET请求(其他答案没有提到你可以指定一个端口变量),你可以使用这个函数:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

不要错过文件顶部的require模块:

http = require("http");
url = require('url')

另外请记住,您可以使用https模块在安全的网络上进行通信。所以这两条线会改变:

https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......

尝试使用简单的http。Get (options, callback)函数在node.js:

var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

还有一个通用的http。请求(选项,回调)函数,允许您指定请求方法和其他请求细节。

看看httpreq:这是我创建的一个节点库,因为我很沮丧,没有简单的http GET或POST模块;-)

Unirest是我遇到的用于从Node发出HTTP请求的最好的库。它的目标是成为一个多平台框架,所以如果你需要在Ruby、PHP、Java、Python、Objective C、. net或Windows 8上使用HTTP客户端,学习它在Node上的工作方式会对你很有帮助。据我所知,unirest库大多是由现有的HTTP客户端支持的(例如,在Java上,Apache的HTTP客户端,在Node上,Mikeal的Request库)——unirest只是在上面放了一个更好的API。

下面是Node.js的一些代码示例:

var unirest = require('unirest')

// GET a resource
unirest.get('http://httpbin.org/get')
  .query({'foo': 'bar'})
  .query({'stack': 'overflow'})
  .end(function(res) {
    if (res.error) {
      console.log('GET error', res.error)
    } else {
      console.log('GET response', res.body)
    }
  })

// POST a form with an attached file
unirest.post('http://httpbin.org/post')
  .field('foo', 'bar')
  .field('stack', 'overflow')
  .attach('myfile', 'examples.js')
  .end(function(res) {
    if (res.error) {
      console.log('POST error', res.error)
    } else {
      console.log('POST response', res.body)
    }
  })

您可以直接跳转到Node文档

Request和Superagent是非常好的库。

注意:请求已弃用,使用风险自负!

使用要求:

var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode === 200 ) //etc
  //TODO Do something with response
});