3

サーバーhttpリスナーを作成しました:

var http = require('http');
http.createServer(function (req, res)
{
        res.writeHead(200,
        {
                'Content-Type': 'text/plain'
        });
        res.write('aaa');
        res.end();
}).listen(1337, '127.0.0.1');
console.log('waiting......');

それは、検索と応答を実行しています。

ここに画像の説明を入力してください

今、私は欲しいです-foreachクライアントリクエスト-サーバーは別のリクエストを実行し、文字列を追加"XXX"します :

だから私は書いた:

var http = require('http');
var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
http.createServer(function (req, res)
{
        res.writeHead(200,
        {
                'Content-Type': 'text/plain'
        });
        res.write('aaa');

        http.request(options, function (r)
        {
                r.on('data', function (chunk)
                {
                        res.write('XXX');
                });
                r.on('end', function ()
                {
                        console.log(str);
                });
                res.end();
        });

        res.end();
}).listen(1337, '127.0.0.1');
console.log('waiting......');

したがって、foreachリクエストでは、次のように記述します:aaaXXX(aaa + XXX)

しかし、それは機能しません。それでも同じ出力を生成しました。

私は何が間違っているのですか?

4

2 に答える 2

1

これを試して:

var http = require('http');
var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
http.createServer(function (req, res)
{
        res.writeHead(200,
        {
                'Content-Type': 'text/plain'
        });
        res.write('aaa');

        var httpreq = http.request(options, function (r)
        {
            r.setEncoding('utf8');
            r.on('data', function (chunk)
            {
                res.write(' - '+chunk+' - ');
            });
            r.on('end', function (str)
            {
                res.end();
            });

        });

        httpreq.end();

}).listen(1337, '127.0.0.1');
console.log('waiting......');

また、nodejitsuに関するこの記事を読む価値があります

于 2012-09-10T09:14:39.503 に答える
0

呼び出しres.end()が早すぎます...すべてが書き込まれたとき(たとえば、r.on('end')が呼び出されたとき)にのみ実行したいのです。

このような場合は、優れたリクエストライブラリ(https://github.com/mikeal/request)を使用することを強くお勧めします。

これには素晴らしいAPIがあります。例:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Print the google web page.
  }
})
于 2012-09-10T08:44:18.593 に答える