node.js将数据发送到客户端?


                    

我想知道如何将数据从node.js发送到客户端吗?</ p>

示例node.js代码-</ p>

  var http = require('http');

var data =“要发送给客户端的数据”;

var server = http.createServer(function(request,response){
   response.writeHead(200,{“ Content-Type”:“ text / plain”});
   response.end(“ Hello World
”);
})。listen(8125);
</ code> </ pre>

现在,我想将 data </ code>变量发送到客户端,并使用JavaScript进行记录。

我该怎么做?
</ p>

谢谢;)</ p>

编辑:</ b>有人知道如何发送数组吗?</ p>
     </ div>

展开原文

原文

I wonder how can I send data from node.js to client?

example node.js code -

var http = require('http');

var data = "data to send to client";

var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World
");
}).listen(8125);

Now, I want to send the data variable to client and log it with JavaScript..
How can I do that?

Thanks ;)

EDIT: Does anyone know how to send array?

1个回答


如果您想在 response.end </ code>之后执行此操作,则应使用 Socket.io 或 服务器发送事件。</ p>

如果要在 res.end </ code>之前使用它,则可以使代码看起来像:</ p>

  var http = require('http');

var data =“要发送给客户端的数据”;

var server = http.createServer(function(request,response){
     response.writeHead(200,{“ Content-Type”:“ text / plain”});
     response.write(数据); //您可以在response.end之前调用Response.write无限次
     response.end(“ Hello World
”);
})。listen(8125);
</ code> </ pre>
     </ div>

展开原文

原文

If You Want to do it after response.end you should use Socket.io or Server Send Events.

If you want it before res.end, you would make your code look like:

var http = require('http');

var data = "data to send to client";

var server = http.createServer(function (request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write(data); // You Can Call Response.write Infinite Times BEFORE response.end
    response.end("Hello World
");
}).listen(8125);

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问