【发布时间】: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