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

浪尽此生 提交于 2020-01-16 08:50:30

问题


GOAL: to have a functioning query search on the react front end.

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.

How can I properly connect the two?


回答1:


You are missing category param in your request to backend. 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 }
        })
    }
}


来源:https://stackoverflow.com/questions/57745960/how-to-get-req-query-value-from-node-js-backend-to-react-redux-front-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!