-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
38 lines (28 loc) · 1015 Bytes
/
app.js
File metadata and controls
38 lines (28 loc) · 1015 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const port = process.env.PORT || 4001;
const index = require("./routes/index");
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server, { cors: { origin: '*' } }); //
// CORS policy 'Access-Control-Allow-Origin' fix https://stackoverflow.com/questions/24058157/socket-io-node-js-cross-origin-request-blocked
let interval;
io.on("connection", (socket) => {
console.log("new client connected");
if (interval) {
clearInterval(interval);
}
interval = setInterval(() => getApiAndEmit(socket), 1000);
socket.on("disconnect", () => {
console.log("Client disconnected");
clearInterval(interval);
});
});
const getApiAndEmit = socket => {
const response = new Date();
// Emitting a new message, will be consumed by client
socket.emit("FromAPI", response);
};
server.listen(port, () => console.log(`Listening on port ${port}`));