-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
50 lines (40 loc) · 1.29 KB
/
server.js
File metadata and controls
50 lines (40 loc) · 1.29 KB
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
import express from 'express';
import ShortUrl from './models/shortUrl.js';
import Connect from './database/mongodb.js';
import * as dotenv from 'dotenv';
import path from 'path';
import {fileURLToPath} from 'url';
dotenv.config()
// Use to get directory
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
console.log('directory-name 👉️', __dirname);
const app = express()
let url = ``
let fullUrl = ``
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'));
app.use(express.urlencoded({extended:false}))
app.get('/',async function(req, res){
// shortUrls = await ShortUrl.find()
res.render("index", {fullUrl: fullUrl, url:url});
url = ``;
fullUrl = ``;
})
app.post('/shortUrls', async function(req, res){
const response = await ShortUrl.create({full: req.body.fullUrl});
url = `http://${req.headers.host}/${response.short}`;
fullUrl = req.body.fullUrl;
res.redirect('/')
})
app.get('/:shortUrl', async function(req, res){
const shortUrl = await ShortUrl.findOne({short: req.params.shortUrl});
if (shortUrl === null){
return res.sendStatus(404);
}
shortUrl.clicks++;
shortUrl.save();
res.redirect(shortUrl.full)
})
app.listen(process.env.PORT || 5000);
Connect();