如何从Node.js后端获取req.query值到React-Redux前端? [英] How to get req.query value from Node.js backend to React-Redux front-end?

查看:43
本文介绍了如何从Node.js后端获取req.query值到React-Redux前端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:在反应前端进行有效的查询搜索.

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

尝试:

后端看起来像这样

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

我写了这样的动作

//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总是具有相同结果的原因.

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.

如何正确连接两者?

推荐答案

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

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

这篇关于如何从Node.js后端获取req.query值到React-Redux前端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆