-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (46 loc) · 1.26 KB
/
index.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
require('dotenv').config()
require('newrelic');
const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const Post = require('./models/post')
const app = express()
morgan.token('body', (req) => JSON.stringify(req.body))
app.use(express.json())
app.use(express.static('build'))
app.use(morgan(':method :url :status :res[content-length] :body'))
app.use(cors())
app.get('/api/posts', (request, response) => {
Post.find({}).then(posts => {
response.json(posts)
})
})
app.get('/api/posts/:id', (request, response) => {
Post.findById(request.params.id)
.then(post => {
if (post) {
response.json(post)
} else {
response.status(404).end()
}
})
})
app.post('/api/posts', (request, response) => {
const body = request.body
const post = new Post({
title: body.title,
content: body.content,
excerpt: body.excerpt,
date: new Date()
})
post
.save()
.then(savedPost => {
response.json(savedPost)
})
}
)
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})