-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
62 lines (52 loc) · 1.5 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
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const config = require("./config");
const path = require("path");
const contacts = require("./contacts");
const app = express();
app.use(express.static("public"));
app.use(cors());
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname + "/client/index.html"));
});
app.use((req, res, next) => {
const token = req.get("Authorization");
if (token) {
req.token = token;
next();
} else {
res.status(403).send({
error:
"Please provide an Authorization header to identify yourself (can be whatever you want)",
});
}
});
app.get("/contacts", async (req, res) => {
res.send(contacts.defaultData.contacts.map((contact) => ({
id: contact.id,
name: contact.name,
email: contact.email
})));
});
app.delete("/contacts/:id", (req, res) => {
res.send(contacts.remove(req.token, req.params.id));
});
app.post("/contacts", bodyParser.json(), (req, res) => {
const { name, email } = req.body;
if (name && email) {
res.send(contacts.add(req.token, req.body));
} else {
res.status(403).send({
error: "Please provide both a name and an email address",
});
}
});
app.listen(config.port, async () => {
try {
console.log("Connection has been established successfully.");
console.log("Server listening on port %s, Ctrl+C to stop", config.port);
} catch (error) {
console.error("Unable to establish the connection:", error);
}
});