-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
87 lines (71 loc) · 2.08 KB
/
Copy pathserver.js
File metadata and controls
87 lines (71 loc) · 2.08 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//___________________
//Dependencies
//___________________
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const db = mongoose.connection;
require("dotenv").config();
const cors = require("cors");
app.use(express.json());
app.use(cors());
//___________________
//Port
const Posts = require("./models/post");
//___________________
// Allow use of Heroku's port or your own local port, depending on the environment
const PORT = process.env.PORT;
//___________________
//Database
//___________________
// How to connect to the database either via heroku or locally
const MONGODB_URI = process.env.MONGODB_URI;
// Connect to Mongo &
// Fix Depreciation Warnings from Mongoose
// May or may not need these depending on your Mongoose version
mongoose.connect(MONGODB_URI, () => {
console.log("connected");
});
// Error / success
db.on("error", (err) => console.log(err.message + " is Mongod not running?"));
db.on("connected", () => console.log("mongo connected: ", MONGODB_URI));
db.on("disconnected", () => console.log("mongo disconnected"));
//___________________
//Middleware
//___________________
//use public folder for static assets
app.use(express.static("public"));
app.use(express.json()); // returns middleware that only parses JSON - may or may not need it depending on your project
//___________________
// Routes
app.post("/CityBook", (req, res) => {
Posts.create(req.body, (err, CreatedPost) => {
res.json(CreatedPost);
});
});
app.get("/CityBook", (req, res) => {
Posts.find({}, (err, foundPost) => {
res.json(foundPost);
});
});
app.delete("/CityBook/:id", (req, res) => {
Posts.findByIdAndRemove(req.params.id, (err, deletedPost) => {
res.json(deletedPost);
});
});
app.put("/CityBook/:id", (req, res) => {
Posts.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true },
(error, updatedPost) => {
res.json(updatedPost);
}
);
});
//___________________
//localhost:3000
//___________________
//Listener debugging
//___________________
app.listen(4000, () => console.log("Listening on port:", PORT));