-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
97 lines (87 loc) · 2.95 KB
/
app.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
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const mongoose = require('mongoose');
const url = 'mongodb://localhost/blogDb';
const User = require('./model/user');
const Post = require('./model/post');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/api/user/login', (req, res) => {
mongoose.connect(url,/*{ useMongoClient: true }, */ { useNewUrlParser: true }, function (err) {
if (err) throw err;
User.find({
username: req.body.username, password: req.body.password
}, function (err, user) {
if (err) throw err;
if (user.length === 1) {
return res.status(200).json({
status: 'success',
data: user
})
} else {
return res.status(200).json({
status: 'fail',
message: 'Login Failed'
})
}
})
});
});
app.post('/api/post/getAllPost', (req, res) => {
mongoose.connect(url, /*{ useMongoClient: true },*/ { useNewUrlParser: true }, function (err) {
if (err) throw err;
Post.find({}, [], { sort: { _id: -1 } }, (err, doc) => {
if (err) throw err;
return res.status(200).json({
status: 'success',
data: doc
})
})
});
});
app.post('/api/post/createPost', (req, res) => {
mongoose.connect(url, /*{ useMongoClient: true },*/ { useNewUrlParser: true }, function (err) {
if (err) throw err;
const post = new Post({
title: req.body.title,
description: req.body.description
})
post.save((err, doc) => {
if (err) throw err;
return res.status(200).json({
status: 'success',
data: doc
})
})
});
});
app.post('/api/post/updatePost', (req, res) => {
mongoose.connect(url, /*{ useMongoClient: true },*/ { useNewUrlParser: true }, function (err) {
if (err) throw err;
Post.update(
{ _id: req.body.id },
{ title: req.body.title, description: req.body.description },
(err, doc) => {
if (err) throw err;
return res.status(200).json({
status: 'success',
data: doc
})
})
});
});
app.post('/api/post/deletePost', (req, res) => {
mongoose.connect(url, /*{ useMongoClient: true },*/ { useNewUrlParser: true }, function (err) {
if (err) throw err;
Post.findByIdAndRemove(req.body.id,
(err, doc) => {
if (err) throw err;
return res.status(200).json({
status: 'success',
data: doc
})
})
});
})
app.listen(3000, () => console.log('blog server running on port 3000!'));