-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
81 lines (66 loc) · 2.18 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
75
76
77
78
79
80
81
"use strict";
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const keys = require("./src/config/keys");
//Models
const User = require("./models/user");
const FoodEntry = require("./models/foodEntry");
//Controllers
const userController = require("./controllers/UserController");
const foodController = require("./controllers/FoodController");
const app = express();
const router = express.Router();
//mLab
const mongoDB = keys.mongoDB;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));
var port = process.env.PORT || 3001;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader(
"Access-Control-Allow-Methods",
"GET,HEAD,OPTIONS,POST,PUT,DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"
);
res.setHeader("Cache-Control", "no-cache");
next();
});
/* ROUTES */
//Initialize the API
router.get("/", function(req, res) {
res.json({ message: "API Initialized!" });
});
//user routes
router
.route("/users")
.post(userController.userSignUp);
router.route("/userLogin").post(userController.userLogin);
router
.route("/foodEntry")
.post(foodController.newEntry)
.delete(foodController.deleteEntry);
router.route("/userFoodEntries").post(foodController.allUserEntries);
app.use("/api", router);
//run this if on heroku
if (process.env.NODE_ENV === "production") {
//express will serve production assets
app.use(express.static("build"));
//express will serve index.html file if it does not know the route
const path = require("path");
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "build", "index.html"));
});
}
app.listen(port, function() {
console.log("api running on port " + port);
});