-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (54 loc) · 1.48 KB
/
index.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
import express from "express";
import axios from "axios";
import { dirname } from "path";
import { fileURLToPath } from "url";
import bodyParser from "body-parser";
import "dotenv/config";
const __dirname = dirname(fileURLToPath(import.meta.url));
const app = express();
const port = 3000;
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: true }));
const API_URL = "https://api.aviationstack.com/v1";
const API_KEY = process.env.API_KEY;
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.post("/get-flight", async (req, res) => {
let config = {};
if (req.body.hasOwnProperty("flight_iata")) {
config = {
params: {
access_key: API_KEY,
flight_iata: req.body.flight_iata,
},
};
} else if (req.body.hasOwnProperty("dep_iata")) {
config = {
params: {
access_key: API_KEY,
dep_iata: req.body.dep_iata,
arr_iata: req.body.arr_iata,
},
};
}
try {
const response = await axios.get(`${API_URL}/flights`, config);
const result = response.data;
if (result.data.length === 0) {
throw {
message: "Flight not found",
};
}
res.render("search.ejs", { results: result.data });
} catch (error) {
console.log(error.message);
res.render("search.ejs", { error: error.message });
}
});
app.get("/search", (req, res) => {
res.render("search.ejs");
});
app.listen(port, () => {
console.log(`Listening on port ${port}.`);
});