forked from SEA-Design-Dev/mean-stack-1
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
104 lines (78 loc) · 1.94 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"use strict";
var express = require("express");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var app = express();
var router = express.Router();
var Blog = require("./models/blog");
mongoose.connect("mongodb://localhost/intelly");
app.set("port", (process.env.PORT || 5000));
app.use(bodyParser.json());
router.get("/", function (req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});
app.use(express.static(__dirname + "/public"));
app.use("/", router);
// CREATE
var blogsRoute = router.route("/api/blogs");
blogsRoute.post(function (req, res) {
var blog = new Blog();
blog.title = req.body.title;
blog.content = req.body.content;
blog.author = req.body.author;
blog.date = req.body.date;
blog.save(function (err) {
if (err) {
res.send(err);
}
res.json(blog);
});
});
// READ
blogsRoute.get(function (req, res) {
Blog.find(function (err, blogs) {
if (err) {
res.send(err);
}
res.json(blogs);
});
});
var blogRoute = router.route("/api/blogs/:blog_id");
blogRoute.get(function (req, res) {
Blog.findById(req.params.blog_id, function (err, blog) {
if (err) {
res.send(err);
}
res.json(blog);
});
});
// UPDATE
blogRoute.put(function (req, res) {
Blog.findById(req.params.blog_id, function (err, blog) {
if (err) {
res.send(blog);
}
blog.title = req.body.title;
blog.content = req.body.content;
blog.author = req.body.author;
blog.date = req.body.date;
blog.save(function (err) {
if (err) {
res.send(err);
}
res.json(blog);
});
});
});
// DELETE
blogRoute.delete(function (req, res) {
Blog.findByIdAndRemove(req.params.blog_id, function(err) {
if (err) {
res.send(err);
}
res.json({ message: "Successfully removed blog." });
});
});
app.listen(app.get("port"), function() {
console.log("Express server is running on port", app.get("port"));
});