Controller for cart
const Cart = require("../models/Cart");
const getCart = (req, res)=> {
Cart.find()
.then((cart) => {
res.status(200).json("hello")
// return "hello"
})
.catch((err) => {
res.json(err)
})
}
const addCart = (req, res) => {
// const cart = new Cart({
// item_id: req.body.item_id,
// quantity: req.body.quantity,
// amount: req.body.amount
// })
const cart = new Cart({
title: req.body.title,
description: req.body.description,
price: req.body.price,
quantity: req.body.quantity
})
cart.save()
.then(() => {
res.json('added to cart')
})
.catch((err) => {
res.json(err)
})
}
module.exports = {
getCart,
addCart
}
Controller for Item
const Item = require("../models/Item");
const getItem = (req, res) => {
Item.find()
.then((item) => {
res.json(item)
})
.catch((err) => {
// console.log(err)
res.json(err)
})
// res.send("I'm item route")
}
const getOneItem = (req, res) => {
// Item.findOne({_id: '6626a3c852da8b83396606aa'})
// .then((item) => {
// res.json(item)
// })
// .catch((err) => {
// res.json(err)
// })
const id = req.params.id;
res.json(id)
}
const createItem =(req, res) => {
const item = new Item({
title: req.body.title,
description: req.body.description,
quantity: req.body.quantity,
price: req.body.price
});
item.save()
.then((item)=>{
console.log('item saved')
res.json(item)
})
.catch((err) => {
res.json(err)
})
}
const deleteItem = (req, res) => {
Item.deleteOne({_id: req.params.id})
.then(() => {
console.log('item deleted')
})
.catch((err) => {
console.log(err)
})
}
const editItem = (req, res) => {
Item.findOneAndUpdate({_id: '6626a3c852da8b83396606aa'},{
$set: {
title: req.body.title,
description: req.body.description,
quantity: req.body.quantity,
price: req.body.price
}
})
.then(() => {
console.log('item updated')
})
.catch((err) => {
console.log(err)
})
}
// const getItem = (req, res) => {
// }
module.exports = {
getItem,
createItem,
deleteItem,
editItem,
getOneItem
}
Router
const router = require("express").Router();
const { getItem, createItem, deleteItem, editItem, getOneItem } = require("./controllers/Item")
const { addCart, getCart } = require('./controllers/cart')
router.get("/", getItem);
router.get("/:id", getOneItem);
router.post("/item", createItem)
router.delete('/:id', deleteItem)
router.put('/edit', editItem)
router.get("/cart", getCart)
router.post('/cart', addCart)
module.exports = router;
The problem is when I try to use the api "http://localhost:3001/cart" I only receive response "cart" while I'm expecting list of data.
The api "http://localhost:3001/" is working fine I'm receiving list of data.
I have tried to used the getItem controller in get request "/cart" and It returned list of data I guess I'm having issue on my getCart controller?
GET /cart
is triggering your /:id
route, not /cart
since the /:id
route was defined first.