ExpressJS_Setup_Guide
ExpressJS_Setup_Guide
const products = [
{ id: 1, name: "mi" },
{ id: 2, name: "iphone" },
{ id: 3, name: "oppo" }
];
app.get('/products', (req, res) => res.json(products));
app.get('/products/:id', (req, res) => {
const product = products.find(p => p.id.toString() === req.params.id);
product ? res.json(product) : res.status(404).json({ message: "Not found" });
});
app.post('/addproducts', (req, res) => {
const { id, name } = req.body;
const newProduct = { id, name };
products.push(newProduct);
res.status(201).json(newProduct);
});
app.put('/updateproducts/:id', (req, res) => {
const product = products.find(p => p.id.toString() === req.params.id);
if (product) {
Object.assign(product, req.body);
res.json(product);
} else res.status(404).json({ message: "Not found" });
});
app.delete('/deleteproducts/:id', (req, res) => {
const index = products.findIndex(p => p.id.toString() === req.params.id);
if (index !== -1) res.json(products.splice(index, 1));
else res.status(404).json({ message: "Not found" });
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Congratulations! You have successfully set up and run an Express.js project in VS Code.