我已经通过这个代码向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)
}
})特定类别的产品显示在react前端的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发送到后台。因此,如果任何人有任何想法,请指导我。
发布于 2020-10-06 13:33:13
查询参数可以在node js中使用get方法,在nodeJs中可以通过req.query获取查询参数
从前端传递类别id的示例-
api/products/categories/filter?cid=1后台获取查询参数
const catId = req.query.cid发布于 2020-10-06 13:36:23
您可以使用以下代码将参数传递给API get方法。
fetch("/api/products/categories/filter?catId" + catId)
.then((res) => res.json())
.then((json) => {
this.setState({
Items: json,
});
});您还可以首先创建名为Items的新状态,如下所示。
this.state = {
Items: []
};最后对项目进行迭代。
BR
https://stackoverflow.com/questions/64219713
复制相似问题