/
server.js
68 lines (54 loc) · 1.93 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
require("dotenv").config();
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const path = require("path");
const mongoose = require("mongoose");
const routes = require("./routes");
const PORT = process.env.PORT || 3001;
const app = express();
//Setting up server and adding socketIo middleware
const server = http.createServer(app);
const io = socketIo(server);
// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
app.use(routes);
// Connect to the Mongo DB
mongoose.connect(
process.env.MONGODB_URI ||
"mongodb://localhost:27017/roadtripdb", { useNewUrlParser: true, useUnifiedTopology: true }
);
// // Send every other request to the React app
// app.get("*", (req, res) => {
// res.sendFile(path.join(__dirname, "./client/build/index.html"));
// });
//Setting up a socket with the namespace "connection" for new sockets
io.on("connection", socket => {
console.log("New client connected");
//Here we listen on a new namespace called "incoming data"
socket.on("incoming data", data => {
console.log(`Logging data, ${data}`);
//Here we broadcast it out to all other sockets EXCLUDING the socket which sent us the data
// socket.broadcast.emit('outgoing data', {
// tripData: data.tripData
// });
// We send the data to everyone, including the sender.
io.emit('incoming data', {
tripData: data.tripData
});
});
//A special namespace "disconnect" for when a client disconnects
socket.on("disconnect", () => console.log("Client disconnected"));
});
//Capture All 404 errors
app.use(function (req, res, next) {
res.status(404).send('Unable to find the requested resource!');
});
server.listen(PORT, () => {
console.log(`🌎 ==> API server now on port ${PORT}!`);
});