Javascript 在NodeJs服务器中发出请求?

Javascript 在NodeJs服务器中发出请求?,javascript,node.js,Javascript,Node.js,我已经创建了一个服务器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.

我已经创建了一个服务器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 client request-服务器执行另一个请求并附加一个字符串
“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......');
所以现在对于每个请求,它应该写:
aaaXXX
(aaa+XXX)

但它不起作用。它仍然输出相同的输出


我怎么了

您调用
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.
  }
})
试试这个:

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......');

另外,值得一读

查找socket.io或类似WebSocket的节点。开箱即用节点仍然只是一个基本的HTTP服务器。实时部分来自WebSockets。@psycketom,但这个基本Http服务器可以自己发出另一个请求。这就是我的问题所在。:)尽管如此,在删除
结束后(第一个)仍然不起作用……为什么他不能发出另一个请求和concat字符串?(我还没有改变你的解决方案。我想弄明白为什么我的手机不工作)我有没有告诉过你——我爱你?:-)谢谢。首先,我删除了
res.end()
,因为前面的
http.request
是异步的,我们应该等待它完成,另一部分是我们需要
.end()
http.request
使它实际执行(我们可以在
.end()之前发布一些数据)
这就是我们使用该方法的原因)为什么调用
res.end()
on
r.on('data',function(chunk)
?@RoyiNamir,说得好,我的错..这应该只在
中。on('end')