我正在使用 Nodejs 和 Express 开发一个客户端-服务器应用程序。我想向所有连接到服务器的客户端发送一个 HTML 页面(例如 index.html
)。
服务器允许用户使用用户名和密码登录,此连接数据存储在一个数组中,如下所示:
app.post('/myaction', function(req, res) {
clients.push({
"name": req.body.nombre,
"direction":req.connection.remoteAddress,
"time": getDate(),
"role" : role
});
}
因此 IP 方向也存储在该数组中。我可以使用 forEach
循环进行循环:
clients.forEach(function (client) {
});
哪个 Express 函数允许我向数组中存储的所有这些客户端发送 HTML 文档?
最佳答案
使用 Express 无法实现这一点。最好的方法是使用 websockets 将数据推送到所有连接的客户端。我建议使用Socket.io因为它使用起来非常简单。
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
io.on('connection', socket => {
console.log('User connected');
});
app.post('/myaction', (req, res) => {
io.emit('data', 'some-data');
res.send('Data sent to all connected users');
});
客户端
// Add socket.io client side library
var socket = io();
socket.on('data', function(data) {
// Do something with the data sent from the server
});
关于javascript - 使用 Express 在 Nodejs 中向客户端广播 HTML 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081476/