-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
74 lines (58 loc) · 1.99 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
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
70
71
72
73
74
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const path = require('path');
const Article = require('./models/article');
const dotenv = require("dotenv");
const cors = require("cors");
const https = require('https');
const fs = require('fs');
const bodyParser = require("body-parser");
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
// initialize app
const app = express();
const PORT = process.env.PORT || 3000;
dotenv.config()
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(require('prerender-node').set('prerenderToken', process.env.PRERENDER_TOKEN));
// connect to mongodb
const MONGODB_URI = `mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@portfoliodb.n5g0z.mongodb.net/?retryWrites=true&w=majority`;
mongoose.connect(MONGODB_URI || 'mongodb://localhost/idadelveloper', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then((result) => https.createServer(options, app)
.listen(PORT, () => {
console.log(`Server is starting at ${PORT}`);
}))
.catch((err) => console.log(err));
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected!!!');
})
// Log http requests
app.use(morgan('tiny'));
app.use(express.static(path.join(__dirname, 'client/build')));
// app routes
app.get('/articles', async(req, res) => {
const articles = await Article.find().sort({ createdAt: 'desc' })
res.json(articles)
})
app.get('/articles/:slug', async(req, res) => {
const slug = req.params.slug
const article = await Article.findOne({ slug: slug })
res.json(article)
})
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
app.get('/home', function(req, res) {
res.redirect('/')
})
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'))
})