问题
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