admin管理员组文章数量:814857
如何通过axios get方法在react中发送参数?
我有一个axios GET方法,我需要在get请求中传递参数。我这样在客户端(React.js)中调用GET方法,
const [Cart] = useState([]);
const user = {
userId : session.userId
};
console.log(user);
useEffect((user) => {
if(session.userId !== null){
//Axios.get('http://localhost:5000/api/cart/getCart', user) <- I tried both these ways
Axios({
method: 'GET',
url: 'http://localhost:5000/api/cart/getCart',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: {},
params: {
"userId" : session.userId
}
})
.then(res => {
const cart = res.data;
let tempProducts = [];
cart.data.forEach(item => {
const singleItem = {...item};
tempProducts = [...tempProducts, singleItem];
});
this.setState(() => {
return {Cart: tempProducts};
});
})
}
console.log(Cart)
});
但是在服务器端(node.js),它没有获取参数值。
router.get('/getCart', (req, res) => {
console.log(req.body.userId) //This gives the output as undefined
User.findOne({_id: req.body.userId}
,(err, userInfo) => {
res.json(userInfo.Cart);
})
});
我通过参考this实现了未注释的axios.get请求。您能帮我找到错误吗?还是可以建议我其他方法来做到这一点?谢谢
回答如下:UseEffect:
axios.get('/api', {
params: {
foo: 'bar'
}
});
服务器:
function get(req, res, next) {
let param = req.query.foo
.....
}
本文标签: 如何通过axios get方法在react中发送参数
版权声明:本文标题:如何通过axios get方法在react中发送参数? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/biancheng/1715129488a821358.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论