-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (92 loc) · 2.19 KB
/
index.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
105
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const path = require("path");
const app = express();
const User = require("./model/UserSchema");
const { json } = require("express");
dotenv.config({ path: "./config.env" });
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
const PORT = process.env.PORT || 5000;
const DB_URI = process.env.DATABASE;
// app.use(express.static(path.join(__dirname, "build")));
// app.get("/*", function (req, res) {
// res.sendFile(path.join(__dirname, "build", "index.html"));
// });
// app.use(express.static(path.join(__dirname, "build")));
// app.get("*", (req, res) => {
// res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
// });
mongoose
.connect(DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
})
.catch((err) => {
console.log(err);
});
app.get("/user", (req, res) => {
User.find({}, function (err, result) {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});
app.post("/add", (req, res) => {
const { name, email, phone } = req.body;
const newUser = new User({
name,
email,
phone,
});
newUser.save().then((data) => {
res.send(data);
//HTTP status code 201 created
res.status(201).json({
message: "User added successfully",
});
});
// User New
});
app.delete("/delete/:id", (req, res) => {
User.findByIdAndDelete(req.params.id, (err, result) => {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});
app.get("/view/:id", (req, res) => {
User.findById(req.params.id, (err, result) => {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});
app.put("/update/:id", (req, res) => {
const { name, email, phone } = req.body;
User.findByIdAndUpdate(
req.params.id,
{ name, email, phone },
(err, result) => {
if (err) {
console.log(err);
} else {
res.json(result);
}
}
);
});