我正在尝试使用node.js发出一个简单的HTTP GET请求,但是使用node.js v0.3.4-pre(即截至今天早上从HEAD编译)时遇到了麻烦。这是我的代码:

    var cli = require('cli');
    var http = require('http');
    var url = require('url');

    cli.parse();

    cli.main(function(args, opts) {
            this.debug(args[0]);

            var siteUrl = url.parse(args[0]);
            var site = http.createClient(siteUrl.port, siteUrl.host);
            console.log(siteUrl);

            var request = site.request("GET", siteUrl.pathname, {'host' : siteUrl.host})
            request.end();

            request.on('response', function(response) {
                    response.setEncoding('utf8');
                    console.log('STATUS: ' + response.statusCode);
                    response.on('data', function(chunk) {
                            console.log("DATA: " + chunk);
                    });
            });
    });

这是我得到的错误:
node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
Error: EAFNOSUPPORT, Address family not supported by protocol family
    at doConnect (net.js:499:19)
    at Client.connect (net.js:652:30)
    at Client._ensureConnection (http.js:1033:10)
    at Client.request (http.js:1048:8)
    at Object.<anonymous> (/Users/paul/Desktop/readify.js:16:21)
    at /usr/local/lib/node/.npm/cli/0.2.3-2/package/cli.js:995:18
    at Object.main (/usr/local/lib/node/.npm/cli/0.2.3-2/package/cli.js:1000:9)
    at Object.<anonymous> (/Users/paul/Desktop/readify.js:10:5)
    at Module._compile (node.js:359:32)
    at Object..js (node.js:367:14)

最佳答案

发现该错误,除非URL明确命名端口,否则siteUrl.port将为undefined。因此,解决方案是:

var site = http.createClient(siteUrl.port || 80, siteUrl.host);

09-25 19:44