如何从Node.js后端获取req.query值到React-Redux前端?

时间:2019-09-01 12:21:00

标签: node.js reactjs redux axios

目标:在react前端进行有效的查询搜索。

尝试

后端看起来像这样

//route: GET /shop
//note: get all the products on shop page
//access: public
router.get('/', async (req, res) => {
    try {
        let items

        //sort by category
        if(!req.query.category) {
            items = await Product.find()
        } else {
            items = await Product.find({category: req.query.category})
        }
        //sort by price and letter
        if(req.query.sortBy) {
            let sort ={}
            const sortByArray = req.query.sortBy.split(':')
            sort[sortByArray[0]] =[sortByArray[1]]
            items = await Product.find().sort(sort).exec()
        }

        res.json(items)
    } catch (error) {
        console.error(error.message)
        res.status(500).send('Server error')
    }
})

它可以在后端的服务器上运行,现在我有一个反应前端,并且将按钮与搜索查询(例如

)链接在一起
<Link to="/shop?category=music" >MUSIC</Link>

我写了这样的动作

//get all the products
export const getProducts = () => async dispatch => {
    try {
        const res = await axios.get('/shop')

        dispatch({
            type: GET_PRODUCTS,
            payload: res.data
        })
    } catch (error) {
        dispatch({
            type: PRODUCT_ERROR,
            payload: { msg: error.response.statusText, status: error.response.status }
        })
    }
}

但是我没有像后端那样得到相同的响应。我认为这是因为React无法处理req.params,这就是为什么axios.get总是具有相同结果的原因。

如何正确连接两者?

1 个答案:

答案 0 :(得分:1)

您在后端请求中缺少category参数。您的操作应如下所示:

export const getProducts = () => async dispatch => {
    try {
        const res = await axios.get(`/shop${window.location.search}`) // This will add your current page url query params to API url so the API url would be: '/shop?category=music'
        dispatch({
            type: GET_PRODUCTS,
            payload: res.data
        })
    } catch (error) {
        dispatch({
            type: PRODUCT_ERROR,
            payload: { msg: error.response.statusText, status: error.response.status }
        })
    }
}