-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
57 lines (46 loc) · 1.3 KB
/
app.js
File metadata and controls
57 lines (46 loc) · 1.3 KB
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
const express = require('express'); //could use var instead of const
const bodyParser = require('body-parser');
const mongojs = require('mongojs');
const db = mongojs('catalog', ['products']);
const app = express();
const port = 3000;
app.use(bodyParser.json()); //middleware for bodyParser
//Home
app.get('/', (req, res, next) => {
res.send('Please use /api/products');
}); //route creation for homepage
// Fetch All Products
app.get('/api/products', (req, res, next) => {
db.products.find((err, docs) => {
if(err){
res.send(err);
}
console.log('Products Found...');
res.json(docs);
});
});
// Fetch Single Product
app.get('/api/products/:id', (req, res, next) => {
db.products.findOne({_id: mongojs.ObjectId(req.params.id)}, (err, doc) => {
if(err){
res.send(err);
}
console.log('Products Found...');
res.json(doc);
});
});
// Add Product
app.post('/api/products/', (req, res, next) => {
res.send('Add Product');
});
// Update Product
app.put('/api/products/:id', (req, res, next) => {
res.send('Update product ' + req.params.id);
});
// Delete Product
app.delete('/api/products/:id', (req, res, next) => {
res.send('Delete product ' + req.params.id);
});
app.listen(port, () => {
console.log('Server started on port '+ port);
}); //this will run the server