-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (70 loc) · 2.01 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const express = require("express");
const exphbs = require("express-handlebars");
const path = require("path");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const Url = require("./models/url.js");
const app = express();
app.use(express.static(path.join(__dirname, "/public")));
app.use(bodyParser.urlencoded({ extended: true }));
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
mongoose.connect(
"mongodb://John:[email protected]:15758/my-mongodb-app"
);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function() {
app.listen(3000, () => {
console.log("Listening on port 3000...");
});
});
app.get("/", (req, res) => {
res.render("index", {});
});
app.post("/urls", (req, res) => {
const shorten = Math.random().toString(36).substr(2, 5);
Url.findOne({ longurl: req.body.longurl }, (err, doc) => {
if (doc) {
res.render("url", { url: doc });
} else {
Url.create(
{
longurl: req.body.longurl,
shorturl: shorten
},
(err, doc) => {
if (err) return console.log(err);
res.render("url", { url: doc });
}
);
}
});
});
// app.post("/urls", (req, res) => {
// const shorten = Math.random().toString(36).substr(2, 5);
// const url = new Url({
// longurl: req.body.longurl,
// shorturl: shorten
// });
// Url.findOne({ longurl: req.body.longurl }, (err, doc) => {
// if (doc) {
// res.render("url", { url: doc });
// } else {
// url.save((err, doc) => {
// if (err) return console.log(err);
// res.render("url", { url: doc });
// });
// }
// });
// });
app.get('/:inputurl', (req, res) => {
let inputurl = req.params.inputurl;
Url.findOne({ shorturl: inputurl}, (err, doc) => {
if (doc) {
res.redirect(doc.longurl);
} else {
res.render('index', { invalidurl: inputurl});
}
})
});