简体   繁体   English

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

[英]How to get req.query value from Node.js backend to React-Redux front-end?

GOAL : to have a functioning query search on the react front end. GOAL :在react前端进行有效的查询搜索。

TRIED : 尝试

Backend looks like this 后端看起来像这样

//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')
    }
})

And it works on the backend's server, now I have a react front end, and I link the button with the search query, such as 而且它可以在后端的服务器上运行,现在我有一个反应前端,并且将按钮与搜索查询链接起来,例如

<Link to="/shop?category=music" >MUSIC</Link>

And I wrote the actions like this 我写了这样的动作

//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 }
        })
    }
}

but I don't get the same response like the backend. 但我没有像后端那样得到相同的响应。 I think it's because React doesn't handle the req.params, that's why my axios.get always has the same result. 我认为这是因为React无法处理req.params,这就是为什么axios.get总是具有相同结果的原因。

How can I properly connect the two? 如何正确连接两者?

You are missing category param in your request to backend. 您在后端请求中缺少category参数。 Your action should look like this: 您的操作应如下所示:

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 }
        })
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM