Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions polling/exercise/backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const getMsgs = () => Array.from(msg).reverse();
// feel free to take out, this just seeds the server with at least one message
msg.push({
user: "brian",
text: "hi",
text: "Backchod Baba Is Chomu",
time: Date.now(),
});

Expand All @@ -21,13 +21,23 @@ app.use(bodyParser.json());
app.use(express.static("frontend"));

app.get("/poll", function (req, res) {
// use getMsgs to get messages to send back
// write code here
res.json({
msg: getMsgs()
});
});

app.post("/poll", function (req, res) {
// add a new message to the server
// write code here
const {user, text} = req.body;

msg.push({
user,
text,
timer: Date.now()
})

res.json({
status: "ok"
})
});

// start the server
Expand Down
31 changes: 29 additions & 2 deletions polling/exercise/frontend/polling-chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,38 @@ chat.addEventListener("submit", function (e) {
async function postNewMsg(user, text) {
// post to /poll a new message
// write code here
const data = {
user,
text,
};

// request options
const options = {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
};

// send POST request
const res = await fetch("/poll", options);
const json = await res.json();

}

async function getNewMsgs() {
// poll the server
// write code here
let json;
try{
const res = await fetch("/poll")
json = await res.json()
}
catch(e){
console.log("Polling Error", e)
}
allChat = json.msg
render()
setTimeout(getNewMsgs, INTERVAL)
}

function render() {
Expand Down
Loading