-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
56 lines (42 loc) · 1.37 KB
/
server.js
File metadata and controls
56 lines (42 loc) · 1.37 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
51
52
53
54
55
56
const express = require('express');
const mongoose = require('mongoose');
const ShortUrl = require('./models/shortUrl');
require('dotenv').config();
const app = express()
const port =process.env.PORT || 5000;
// const uri = process.env.ATLAS_URI;
// mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology:true, useCreateIndex:true})
// const connection = mongoose.connection;
// connection.once('open',() => {
// console.log("MongoDB database connection established sucessfully");
// })
mongoose.connect("mongodb://localhost:/urls",{ useNewUrlParser:true, useUnifiedTopology: true},(error)=>{
if(!error)
{
console.log("Succefully connect to the urls DB");
}
else
{
console.log("Error to Stablish Connection");
}
});
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.post('/shortUrls', async (req,res) => {
await ShortUrl.create({full: req.body.inputurl })
res.redirect('/')
})
app.get('/:shortUrl', async (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(port || 5000 , () => {
console.log(`Server is running on port: ${port}`)
});