我们如何使用通过axios接收的数据将请求放在客户端的mern堆栈中



我已经通过这个代码向Nodejs发送了类别Id

const catHandler = async (catId) => {
const data =  Axios.put('/api/products/categories/filter',  {catId: catId},
{ 
"headers": { "content-type": "application/json", },
}
).then( categoriesProducts => {
console.log(categoriesProducts.data.products)
})
}

这是我去的路线

router.put('/categories/filter', async (req, res) => {
try {
const findCategory = await Category.find({ _id: req.body.catId });
if (findCategory) {
const productsByCategory = await Product.find(
{ category: req.body.catId }
).then(products => {
res.status(200).json({ products });
})
}
} catch (error) {
console.log('categories filter error', error)
}
})

特定类别的产品显示在反应前端侧的console.log(categoriesProducts.data.products)中,如下方

0: {_id: "5f7c88756746363148792982", name: "Simple Pizza", price: 5.6, image: "1601996916374.jpg", countInStock: 434, …}
1: {_id: "5f7c88976746363148792983", name: "Smoked Pizza", price: 7.8, image: "1601996951114.jpg", countInStock: 88, …}
2: {_id: "5f7c88c56746363148792984", name: "Large Cheezy Pizza", price: 9.4, image: "1601996997474.jpg", countInStock: 434, …}

但我想在前端展示这些产品。我已经尝试过使用axios.get方法,但使用get方法,我如何才能将类别Id发送到后端。所以,如果有人知道如何做到这一点,Plz会指导我。

您可以在nodejs中使用带有get方法的查询params您可以通过nodeJs 中的req.query获取查询参数

示例从前端传递类别id-

api/products/categories/filter?cid=1

在后端中获取查询参数

const catId = req.query.cid

您可以使用下面的代码将参数传递给API get方法。

fetch("/api/products/categories/filter?catId" + catId)
.then((res) => res.json())
.then((json) => {
this.setState({
Items: json,
});
});

此外,您还可以首先创建名为Items的新状态,如下所示。

this.state = {
Items: []
};

最后在项目上迭代。

BR

最新更新