-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
52 lines (44 loc) · 1.39 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
51
52
const express = require("express");
const path = require("path");
const mongoose = require("mongoose");
const shortUrl = require("./models/shortUrl");
mongoose.connect("mongodb://localhost:27017/urlShortner", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
console.log("vadiya");
});
db.dropDatabase();
const app = express();
app.use(express.json());
// allowing express to take userInput url
app.use(express.urlencoded({ extended: false }));
// setting up daynamic hbs file for rendering html page
app.set("view engine", "hbs");
// setting routes fnding all urls and sending it to index.hbs
app.get("/", async (req, res) => {
const shortUrls = await shortUrl.find();
if (shortUrls.length > 10) {
db.dropDatabase();
}
console.log(shortUrls);
res.render("index", { shortUrls: shortUrls });
});
// creating url and short url by using post method
app.post("/shortUrls", async (req, res) => {
await shortUrl.create({ full: req.body.fullUrl });
res.redirect("/");
});
//taking url that entered and using it
app.get("/:Url", async (req, res) => {
const url = await shortUrl.findOne({ short: req.params.Url });
if (url == null) return res.sendStatus(404);
url.save();
res.redirect(url.full);
});
app.listen("3000", () => {
console.log("server is on");
});