我有一个应用程序应该实时更新来自 websocket API 的一些数据。当我在服务器端 console.log 时会显示此数据。我尝试将它存储在一个变量中并通过 Socket.io 的发射函数传递它。但是当我尝试让数据显示在前端时,它会给出一个空值。
我做错了什么,它不会显示在页面上?
服务器端代码:
app.get("/", function(req, res){
res.render("home");
});
app.get("/fat-finger", function(req, res){
binance.prices((error, ticker) => {
var prijzen = ticker;
res.render("fat-finger", {laatstePrijzen: prijzen});
});
});
app.set('port', process.env.PORT || 3000);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'));
console.log("Server is up and running!")
io.on('connection', function(client) {
console.log('Client connected...');
var coinData;
binance.websockets.prevDay('BTCUSDT', (error, response) => {
coinData = response;
console.log(coinData);
});
io.emit('coins', coinData); //this code sending data from server to client
});
前端代码(客户端):
<% include partials/header %>
<header class="ui main container">
<h1>Fat Finger Scanner</h1>
</header>
<main class="ui text container">
<section class="ui container segment">
<h4>You can find Fat Fingers quickly with this tool!</h4>
<div id="coindatadiv">
<script>
var div = document.getElementById("coindatadiv");
socket.on("connect", function(allCoinData){
div.innerHTML += "<p>"+allCoinData+"</p>";
});
</script>
</div
</section>
</main>
</div>
<% include partials/footer %>
套接字连接正确,因此这不应该是设置两侧的问题。我唯一遇到的问题是将数据从服务器传递到客户端,并能够在页面上实时显示数据更新本身。