-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
67 lines (60 loc) · 1.56 KB
/
app.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
var express = require('express'),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
random = require('random-key');
// mongoose.connect("mongodb://localhost/url_shortener");
mongoose.connect("mongodb://pranav:password@ds117178.mlab.com:17178/url_shortener");
var app = express();
//app.set('port', (process.env.PORT || 3000));
app.set('view engine','ejs');
app.set('views',__dirname + '/views');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + "/public"));
// Schema Setup
var urlSchema = new mongoose.Schema({
shortUrl: String,
longUrl: String
});
var Url = mongoose.model("Url",urlSchema);
// Home Page
app.get('/',function(req,res){
res.render('index');
});
// Shorten link
app.post('/shorten',function(req,res){
var urlInput = req.body.long;
var key = random.generate(5);
var newurl = {
shortUrl: key,
longUrl: urlInput
}
Url.create(newurl,function(err,url){
if(err)
console.log(err);
else{
console.log("URL added in database");
res.send(req.headers.origin + "/" + key);
}
});
});
// Redirect to longURL
app.get('/:key',function(req,res){
var short = req.params.key;
if(short.length!=5)
res.redirect('/');
Url.find({'shortUrl': req.params.key},function(err,url){
if(err)
console.log(err);
else{
//console.log(url);
var long = url[0]['longUrl'];
res.redirect(long);
}
});
});
// app.listen(app.get('port'), function () {
// console.log('listening on port ' + app.get('port'));
// });
app.listen(3000,function(){
console.log("Server started on port 3000");
});