-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
103 lines (85 loc) · 2.53 KB
/
server.js
File metadata and controls
103 lines (85 loc) · 2.53 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
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
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// In-memory storage for products
let products = [
{
id: 1,
name: "Premium Headphones",
price: 199.99,
image: "https://via.placeholder.com/300x200/4F46E5/ffffff?text=Headphones",
description: "High-quality wireless headphones with noise cancellation"
},
{
id: 2,
name: "Smart Watch",
price: 299.99,
image: "https://via.placeholder.com/300x200/059669/ffffff?text=Smart+Watch",
description: "Advanced fitness tracking and smartphone integration"
},
{
id: 3,
name: "Laptop Stand",
price: 49.99,
image: "https://via.placeholder.com/300x200/DC2626/ffffff?text=Laptop+Stand",
description: "Ergonomic aluminum laptop stand for better posture"
}
];
let nextId = 4;
// API Routes
app.get('/api/products', (req, res) => {
res.json(products);
});
app.post('/api/products', (req, res) => {
const { name, price, image, description } = req.body;
if (!name || !price) {
return res.status(400).json({ error: 'Name and price are required' });
}
const newProduct = {
id: nextId++,
name,
price: parseFloat(price),
image: image || 'https://via.placeholder.com/300x200/6B7280/ffffff?text=No+Image',
description: description || ''
};
products.push(newProduct);
res.status(201).json(newProduct);
});
app.put('/api/products/:id', (req, res) => {
const id = parseInt(req.params.id);
const { name, price, image, description } = req.body;
const productIndex = products.findIndex(p => p.id === id);
if (productIndex === -1) {
return res.status(404).json({ error: 'Product not found' });
}
products[productIndex] = {
id,
name,
price: parseFloat(price),
image,
description
};
res.json(products[productIndex]);
});
app.delete('/api/products/:id', (req, res) => {
const id = parseInt(req.params.id);
const productIndex = products.findIndex(p => p.id === id);
if (productIndex === -1) {
return res.status(404).json({ error: 'Product not found' });
}
products.splice(productIndex, 1);
res.status(204).send();
});
// Serve the main app for all other routes (SPA support)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
});