-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
69 lines (59 loc) · 1.86 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
68
69
const express = require('express')
const app = express()
const port = 3000
const SERVER = ` http://localhost:${port}/`
const exphbs = require('express-handlebars')
const Url = require('./models/url') //schema
const shortCode = require('./public/javascripts/shortener') //五亂碼
const mongoose = require('mongoose')
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', () => {
console.log('mongodb error!')
})
db.once('open', () => {
console.log('mongodb connected!')
})
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.engine('hbs', exphbs({ defaultLayout: 'main', extname: '.hbs' }))
app.set('view engine', 'hbs')
// 首頁路由設定
app.get('/', (req, res) => {
res.render('index')
})
// 產生短網址(不重複產生)
app.post('/', (req, res) => {
if (!req.body.originalURL) return res.redirect("/")
const originalURL = req.body.originalURL
Url.findOne({ originalURL })
.then(data => {
if (data) {
res.render('index', { originalURL, shortURL: data.shortURL })
} else {
const shortURL = SERVER + shortCode()
Url.create({ originalURL, shortURL })
.then(newData => {
res.render('index', { originalURL, shortURL })
})
.catch(err => console.log('err: newData'))
}
})
.catch(err => console.log('err: data'))
})
// 將短網址連至原網址
app.get('/:shortCode', (req, res) => {
const shortCode = req.params.shortCode
const shortURL = SERVER + shortCode
Url.findOne({ shortURL })
.then(data => {
res.redirect(data.originalURL)
})
.catch(err => console.log('err'))
})
app.listen(port, () => {
console.log(`App is running on http://localhost:${port}`)
})