-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
70 lines (62 loc) · 1.98 KB
/
server.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
cors: {
origin: "http://127.0.0.1:5500", // or your frontend origin
methods: ["GET", "POST"],
},
});
const cors = require("cors");
const axios = require("axios");
app.use(
cors({
origin: "http://127.0.0.1:800", // or your frontend origin
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true, // enable set cookie
})
);
app.get("/", (req, res) => {
res.send("<h1>Hello World</h1>");
});
io.on("connection", (socket) => {
console.log("a user connected");
socket.emit("serverEvent", socket.id);
socket.on("disconnect", () => {
console.log("user disconnected");
});
socket.on("customEvent", async (data) => {
console.log(data);
try {
// Make API request using Axios (or any other HTTP library)
const response = await axios.get(
"https://1cf8-180-183-230-85.ngrok-free.app/api/v1/employees/list"
);
// Emit the API response back to the client
socket.emit("empData", response.data);
} catch (error) {
console.error("Error fetching data from API:", error.message);
// Emit an error event to the client
socket.emit("apiError", { message: "Error fetching data from API" });
}
});
socket.on("empScan", async () => {
try {
// Make API request using Axios (or any other HTTP library)
const response = await axios.get(
"https://1cf8-180-183-230-85.ngrok-free.app/api/v1/employees/list"
);
// Emit the API response back to the client
socket.emit("updateEmp", response.data);
} catch (error) {
console.error("Error fetching data from API:", error.message);
// Emit an error event to the client
socket.emit("apiError", { message: "Error fetching data from API" });
}
});
});
server.listen(80, () => {
console.log("listening on *:80");
});