简体   繁体   中英

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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