-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.cjs
More file actions
65 lines (56 loc) · 1.82 KB
/
app.cjs
File metadata and controls
65 lines (56 loc) · 1.82 KB
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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const path = require("path");
const buildPath = path.join(__dirname, "build");
// Importing routes
const shortener = require("./routes/api.cjs");
const connectDB = require("./config/connectDB.cjs");
// Importing the URL model
const URL = require("./model/url.cjs");
// Initialising Middleware
const app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(express.static(buildPath));
// Connect to database
connectDB();
// Initialising the routes
app.use("/api/short", shortener);
// TODO: Add a route to redirect to the original URL
app.get("/:shortUrl", (req, res) => {
const shortURL = req.params.shortUrl;
console.log(shortURL.toLowerCase());
URL.findOne({ shortUrl: shortURL.toLowerCase() })
.then((url) => {
if (url) {
console.log("URL found in the database");
const urlRedirect = url.longUrl;
console.log(urlRedirect);
const urlRedirectFormatted = "https://" + urlRedirect;
console.log(urlRedirectFormatted);
res.redirect(urlRedirectFormatted);
//TODO: Redirect to the original URL
} else {
console.log("URL not found in the database");
res.send("URL not found in the database");
}
})
.catch((err) => {
console.log(err);
});
});
// //Serve static files from the React frontend app
app.get("/", (req, res) => {
res.sendFile(path.join(buildPath, "index.html"));
});
// Define a catch-all route to serve the React app's HTML file
app.get("*", (req, res) => {
res.sendFile(path.join(buildPath, "index.html"));
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});