-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
57 lines (46 loc) · 1.5 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
import express from 'express';
import data from './data';
import dotenv from 'dotenv';
import config from './config';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import userRoute from './routes/userRoute';
import productRoute from './routes/productRoute';
const path = require('path');
dotenv.config();
const mongodbUrl = config.MONGODB_URI;
mongoose.connect(mongodbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then( () => {
console.log('Connected to database ')
}).catch(error => console.log(error.reason));
const app = express();
app.use(bodyParser.json());
app.use("/api/users", userRoute);
app.use("/api/products", productRoute);
app.get("/api/products/:id", (req, res) => {
const productId = req.params.id;
const product = data.products.find(x => x._id === productId);
if (product)
res.send(product);
else
res.status(404).send({ msg: "Product Not Found." });
});
app.get("/api/users", (req, res) => {
res.send("Users can't be shown 😅");
})
app.get("/api/products", (req, res) => {
res.send(data.products);
});
// Serve static assets if in production
if (process.env.NODE_ENV === 'production') {
//Set a static folder
app.use(express.static('frontend/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => { console.log('Server started on', port) });