[英]404 not found (API url not found even though it 100% exists)
I'm trying to get a product by id.我正在尝试通过 id 获取产品。 Now when I tried this with postman it worked perfectly fine no problems whatsoever.
现在,当我用 postman 尝试这个时,它工作得非常好,没有任何问题。 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.
但是,当我尝试使用 Angular 获取数据时,它没有工作,它一直说 404 not found 我不知道是什么问题。 Please if anyone knows tell me.
请有知道的人告诉我。 Any help will be appreciated.
任何帮助将不胜感激。 Here's my code.
这是我的代码。
express.js:快递.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: Angular:
now the angular service:现在 angular 服务:
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.您使用了查询参数而不是 url 参数。 It should be
"products/get-product/"+id
:它应该是
"products/get-product/"+id
:
getProductById(id: any){
return this.http.get<Products[]>(
environment.api + "products/get-product/"+id
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.