-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
82 lines (67 loc) · 2.46 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
71
72
73
74
75
76
77
78
79
80
81
82
// ========================
// Packages - using ES Modules
// ========================
// Import the express module. It's a function.
import express from "express";
// Run the Express function.
const app = express();
// Since we are using node with ES Modules, we need to import:
// "path" - node module for working with files & directories.
// "fileURLToPath" - node module that splits web address into readable parts.
// "process" - node global object gives info & control of current node process.
import path from "path";
import { fileURLToPath } from "url";
import process from "process";
// We need to create the __filename & __dirname global objects, native to node.
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// ========================
// Middlewares
// ========================
// Single page app fix.
// Solves problem where browser cannot find static pages
// after build because app is really one page and routes are mocked.
// Using Express' built-in middleware function static(),
// we tell Express to serve static files from the "dist" directory.
app.use(express.static(__dirname + "/dist/"));
// ========================
// Routes
// ========================
// Access token, using environmental variables.
const token = process.env.APP_TOKEN;
// Route route with error handling.
app.get("/alerts/:id", (req, res) => {
const parkId = req.params.id;
fetch(`https://developer.nps.gov/api/v1/alerts?parkCode=${parkId}&parkCode=&api_key=${token}`)
.then(res => {
if (!res.ok) {
throw new Error(res.status);
} else {
return res.json();
}
})
.then((data) => {
res.send(data);
})
.catch((error) => {
const reason = error.message;
res.sendStatus(reason);
});
});
// If none of the above routes' match component's request, it gets handled here.
// We tell Express to send any route request to the app's index.html file.
// Essentially, we deliver the request to Vue and let Vue handle routing.
app.get(/.*/, function (req, res) {
res.sendFile(__dirname + "/dist/index.html");
});
// ========================
// Listen
// ========================
// Remote environment.
app.listen(process.env.PORT, () => {
console.log(`Server listening on port ${process.env.PORT}`);
});
// Local environment.
/* app.listen(4040, () => {
console.log("Server listening on port 4040");
}); */