-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
50 lines (41 loc) · 1.04 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
const express = require("express");
const mongoose = require("mongoose");
const urlShortener = require("./models/urlShortener");
require("dotenv").config();
const app = express();
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
app.set("view engine", "ejs");
app.use(express.json());
app.get("/", (req, res) => {
res.render("index");
});
app.post("/shortUrls", async (req, res) => {
await urlShortener.create(
{
fullUrl: req.body.url,
},
(err, urlShortener) => {
res.send({
shortURL: `${process.env.APP_URL}${urlShortener.shortUrl}`,
});
}
);
});
app.get("/:shortURL", async (req, res) => {
const shortUrl = await urlShortener.findOne({
shortUrl: req.params.shortURL,
});
if (!shortUrl) {
return res.sendStatus(404);
}
let url = shortUrl.fullUrl;
if (!url.includes("http://") && !url.includes("https://")) {
url = `http://${url}`;
}
res.status(301).redirect(url);
});
app.listen(process.env.PORT || 5000);