-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
78 lines (67 loc) · 1.65 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
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const dotenv = require("dotenv");
const cors = require("cors")
// Load env vars
dotenv.config();
// Port number
const PORT = process.env.PORT || 6000;
const BASE_URL = process.env.BASE_URL || "http://localhost:6000";
// Middlewares
app.use(cors())
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Connect to MongoDB
mongoose.connect(
process.env.MONGO_URI,
{ useNewUrlParser: true }
);
// Create a schema
const productSchema = new mongoose.Schema({
name: String,
image: Array,
projectName: String,
price: Number
});
// Create a model
const Product = mongoose.model("Product", productSchema);
// Create a document
app.get("/", (req, res) => {
res.send("Hello World!");
});
// Get all items
app.get("/api/items", (req, res) => {
Product.find({})
.exec()
.then((data) => {
res.send(data);
})
.catch((err) => {
console.log(err);
res.status(500).send("Internal Server Error");
});
});
app.post("/items", (req, res) => {
try {
const itemName = req.body.name;
const itemPrice = req.body.price;
const item = new Product({
name: itemName,
price: itemPrice,
});
console.log("Item: ", item);
item.save().then(() => {
console.log("New item created");
res.send("New item created");
});
} catch (error) {
console.log(error);
res.status(500).send("Internal Server Error");
}
});
app.listen(PORT, () => {
console.log(`Example app listening on port ${PORT}!`);
});