如何解决404 not found (API url not found 即使它 100% 存在)
我正在尝试通过 ID 获取产品。现在,当我与邮递员一起尝试此操作时,它运行得非常好,没有任何问题。但是,当我尝试使用 Angular 获取数据时,它不起作用,它一直说 404 not found 我不知道是什么问题。请知道的人告诉我。任何帮助将不胜感激。这是我的代码。
express.js:
路线:
router.get("/get-product/:id",async (req,res) => {
await fetchProductById(req,res);
});
工具:
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,});
}
} else {
res.status(400).json({
prod,message: "couldn't find any product",id: req.id,success: false,});
}
};
角度:
现在是 Angular 服务:
getProductById(id: any){
return this.http.get<Products[]>(
environment.api + "products/get-product?id="+id
)
}
订阅组件内的服务:
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)
}
)
解决方法
您使用了查询参数而不是 url 参数。应该是"products/get-product/"+id
:
getProductById(id: any){
return this.http.get<Products[]>(
environment.api + "products/get-product/"+id
)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。