【问题标题】:How to send parameters through axios get method in react?react中如何通过axios get方法发送参数?
【发布时间】:2020-08-24 22:38:24
【问题描述】:

我有一个 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请求。你能帮我找出错误吗?或者你能建议我用其他方法吗?谢谢

【问题讨论】:

    标签: node.js reactjs get axios


    【解决方案1】:

    使用效果:

     axios.get('/api', {
              params: {
                foo: 'bar'
              }
            });
    

    服务器:

    function get(req, res, next) {
    
      let param = req.query.foo
       .....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-23
      • 2010-12-23
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      相关资源
      最近更新 更多