I'm trying to get a product by id. Now when I tried this with postman it worked perfectly fine no problems whatsoever. But, when I tried to get the data with Angular it didn't work it keeps saying 404 not found I don't know what's the problem. Please if anyone knows tell me. Any help will be appreciated. Here's my code.
express.js:
route:
router.get("/get-product/:id", async (req, res) => {
await fetchProductById(req, res);
});
utils:
const fetchProductById = async (req, res) => {
const id = req.params.id;
const prod = await Product.findOne({_id: id});
if (prod) {
if (prod.length == 0)
res.status(200).json({
message: "No Products",
success: true,
});
else {
res.status(200).json({
prod,
success: true,
});
}
} else {
res.status(400).json({
prod,
message: "couldn't find any product",
id: req.id,
success: false,
});
}
};
Angular:
now the angular service:
getProductById(id: any){
return this.http.get<Products[]>(
environment.api + "products/get-product?id="+id
)
}
subscribing to the service inside a component:
let id = this.route.snapshot.params.id;
this._product.getProductById(id).subscribe(
(data: Products[])=>{
console.log(data)
},
error => {
console.log("there has been an error trying to fetch this product: "+id)
}
)
You used a query parameter instead of an url parameter. It should be "products/get-product/"+id
:
getProductById(id: any){
return this.http.get<Products[]>(
environment.api + "products/get-product/"+id
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.