Javascript node.js 向客户端发送数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14916743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:19:15  来源:igfitidea点击:

node.js send data to client?

javascriptajaxnode.js

提问by julian

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

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

example node.js code -

示例 node.js 代码 -

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\n");
}).listen(8125);

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

现在,我想将data变量发送到客户端并使用 JavaScript 记录它。
我该怎么做?

Thanks ;)

谢谢 ;)

EDIT:Does anyone know how to send array?

编辑:有谁知道如何发送数组?

回答by Ari Porad

If You Want to do it after response.endyou should use Socket.ioor Server Send Events.

如果你想在response.end你应该使用Socket.io或服务器发送事件之后再做

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

如果你之前想要它res.end,你会让你的代码看起来像:

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\n");
}).listen(8125);