-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (55 loc) · 1.46 KB
/
Copy pathserver.js
File metadata and controls
62 lines (55 loc) · 1.46 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
57
58
59
60
61
62
const { Car, Comment } = require('./models')
const routes = require('./routers')
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const logger = require('morgan')
const path = require('path')
const PORT = process.env.PORT || 3001
const db = require('./db')
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use(logger('dev'))
app.use('/comments', routes)
app.get('/api/cars', async (req, res) => {
const cars = await Car.find()
res.json(cars)
})
app.get('/api/comments', async (req, res) => {
const comments = await Comment.find()
res.json(comments)
})
app.get('/api/cars/:id', async (req, res) => {
try {
const { id } = req.params
const car = await Car.findById(id)
//res.json(car)
if (!car) throw Error('Car not found')
res.json(car)
} catch (e) {
console.log(e)
res.send('Car not found!')
}
})
app.post('/postcar', async (req, res) => {
try {
const car = await new Car(req.body)
console.log(req.body)
await car.save()
return res.status(201).json({
car
})
} catch (error) {
return res.status(500).json({ error: error.message })
}
})
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')))
app.get('*', (req, res) => {
res.sendFile(path.join(`${__dirname}/client/build/index.html`))
})
}
app.listen(PORT, () => {
console.log(`Express server listening on port ${PORT}`)
})