6
var http = require('http');

var options = {
    method: 'GET',
    host: 'www.google.com',
    port: 80,
    path: '/index.html'
};

http.request(
    options,
    function(err, resBody){
        console.log("hey");
        console.log(resBody);
        if (err) {
            console.log("YOYO");
            return;
        }
    }
);

何らかの理由で、これはタイムアウトになり、コンソールに何も記録されません。

できることは承知していますが、使用しているプラ​​グインと互換性を保つrequire('request')ために使用する必要があります。http

また、私のバージョンの背景: Node is v0.8.2

4

3 に答える 3

3

次の例を使用してください: http://nodejs.org/api/http.html#http_http_request_options_callback

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

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

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

コールバックにはエラー パラメータがありません。on("error", ...) を使用する必要があり、end() を呼び出すまでリクエストは送信されません。

于 2013-02-12T22:35:02.050 に答える
0

ここでいくつかのこと:

  • hostname互換性がないhostように使用しないでくださいurl.parse()ここを参照
  • リクエストのコールバックは、1つの引数を取ります。http.ClientResponse
  • エラーをキャッチするには、req.on('error', ...)
  • 使用http.requestする場合は、完了時にリクエストを終了する必要があります。これにより、リクエストを終了する前に、必要な本文を(で) req.end()書き込むことができます。req.write()
    • 注:http.get()これは内部で実行されます。これが、忘れた理由である可能性があります。

作業コード:

var http = require('http');

var options = {
    method: 'GET',
    hostname: 'www.google.com',
    port: 80,
    path: '/index.html'
};

var req = http.request(
    options,
    function(res){
        console.log("hey");
        console.log(res);
    }
);

req.on('error', function(err) {
  console.log('problem', err);
});

req.end();
于 2013-02-12T22:40:30.590 に答える