-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
59 lines (42 loc) · 1.38 KB
/
app.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
"use strict";
const express = require("express");
const ejs = require("ejs");
const bodyParser = require("body-parser");
const app = express();
const cleanUrl = require("./api/cleanUrl");
const testUrl = require("./api/testUrl");
const shortenUrl = require("./api/shortenUrl");
const findUrl = require("./api/findUrl");
const port = process.env.PORT || 2020;
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(express.static("public"));
app.set("view engine", "ejs");
app.get("/", function(req, res) {
res.render("index", {error: ""});
});
app.get("/:word", function(req, res) {
const word = req.params.word;
findUrl(word, function(err, entry) {
if (err) {
return res.render("index", {error: err});
}
res.redirect(entry.url);
});
});
app.post("/shorten", urlencodedParser, function(req, res) {
const url = cleanUrl(req.body.url);
testUrl(url, function(err) {
if (err) {
return res.render("index", {error: err});
}
shortenUrl(url, function(err, entry) {
if (err) {
return res.render("index", {error: err});
}
res.render("result", {url: `http://${req.headers.host}/${entry.word}`})
});
});
});
app.listen(port, function() {
console.log(`App listening on port ${port}`);
});