【问题标题】:Is it possible to update a page for all users on it using only an express server?是否可以仅使用快速服务器为所有用户更新页面?
【发布时间】:2020-07-03 22:22:13
【问题描述】:

我正在构建一个网络应用程序,其中一个功能是将歌曲添加到歌曲队列中。基本上有几个不同的房间,每个房间属性(包括歌曲队列)都以数组的形式存储在服务器上。我使用 app.post 向服务器发送新歌曲 url,然后服务器使用该 url 并将其添加到适当的房间。

现在,当有人将歌曲添加到队列中时,只会更新他们的页面。同一个房间的其他人不会收到这些更新,除非他们添加了自己的歌曲并且服务器将新歌曲队列返回给他们(每次有人添加歌曲时服务器都会返回更新的歌曲队列)。

我相信有一种方法可以使用 socket.io 进行实时更新,但我时间紧迫,想知道是否有一种方法可以使用纯 express node.js 实现预期结果,所以我不需要改变一切。

后端:

let rooms = [];

//other stuff that makes these things functional

/***ADD TO QUEUE***/
app.post('/api/addToQueue', async (req,res) => {
    console.log('Add To Queue Request Recieved');
    const activeRoom = req.body.activeRoom;
    const enteredURL = req.body.enteredURL;
    let newQueue;
    for(let i = 0; i < rooms.length; i++){
        //locates the room to update
        if(rooms[i].roomCode === activeRoom){
            rooms[i].songQueue.push(enteredURL);
            console.log('Updated Queue');
            newQueue = rooms[i].songQueue;
            break;
        }
    }
    res.json(newQueue);
    console.log('Sent New Queue');
    console.log(rooms);
});

前端

//inside the add to queue button component which contains the input bar as well
addToQueue = async () => {
        const activeRoom = this.props.getRoom();
        await fetch('/api/addToQueue', {
            method: "post",
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({activeRoom: activeRoom, enteredURL: this.state.enteredURL})
        })
        .then(res => res.json())
        .then(newQueue => this.props.onAddToQueue(newQueue));
        //onAddToQueue changes the state of another component which then renders in the added song as a 
        paragraph element.
    }

我的文件路径在后端中有我的前端。

希望得到一些帮助:) TIA

【问题讨论】:

    标签: node.js reactjs express server


    【解决方案1】:

    您可以添加 setInterval() 内置函数,每隔几秒运行一次以检查值是否更新。 这样当一个人将一首歌曲添加到队列中时,同一房间中的其他人可以收到这些更新。

    【讨论】:

      【解决方案2】:

      实时网络应用有 3 个选项

      1. 套接字:如果您需要双向通信
      2. 服务器发送事件:只有服务器可以向前端发送信息
      3. 轮询:每隔一定时间向服务器发出请求

      前两个需要更改服务器(第二个更容易),第三个只是前端更改。它们各有优缺点,但我相信您可以找到它们并做出决定。

      【讨论】:

      • 我会全部看看。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 2020-10-26
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多