简体   繁体   English

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

[英]node.js send data to client?

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 data variable to client and log it with JavaScript.. 现在,我想将data变量发送到客户端并使用JavaScript进行记录。
How can I do that? 我怎样才能做到这一点?

Thanks ;) 谢谢 ;)

EDIT: Does anyone know how to send array? 编辑:有谁知道如何发送数组?

If You Want to do it after response.end you should use Socket.io or Server Send Events. 如果您想在response.end之后执行此操作,则应使用Socket.io或Server Send Events。

If you want it before res.end , you would make your code look like: 如果你想在res.end之前使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM