[英]How to get req.query value from Node.js backend to React-Redux front-end?
GOAL :在react前端進行有效的查詢搜索。
嘗試 :
后端看起來像這樣
//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')
}
})
而且它可以在后端的服務器上運行,現在我有一個反應前端,並且將按鈕與搜索查詢鏈接起來,例如
<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總是具有相同結果的原因。
如何正確連接兩者?
您在后端請求中缺少category
參數。 您的操作應如下所示:
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.