-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
42 lines (35 loc) · 1.02 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
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const shortUrl = require('./models/urlShortner');
mongoose.connect('mongodb://localhost/UrlShortner', {
useUnifiedTopology: true,
useNewUrlParser: true
});
app.set('view engine','ejs');
app.use(express.urlencoded({ extended:false }));
app.get('/',async(req, res) => {
const shortUrls = await shortUrl.find();
res.render('index', { shortUrls: shortUrls })
});
app.get('/:url',async(req, res) => {
try {
const url = await shortUrl.findOne({ shortUrl: req.params.url });
if(!url){
res.sendStatus(404);
} else {
url.count++;
console.log(shortUrl);
url.save();
res.redirect(url.actualUrl);
}
} catch(e) {
console.log('e', e);
}
});
app.post('/short-url',async(req, res) => {
await shortUrl.create({ actualUrl: req.body.fullUrl});
res.redirect('/');
});
app.listen(process.env.PORT || 3000);
module.exports = app;