首页 > 解决方案 > 带有参数的axios获取请求不起作用

问题描述

我正在将参数传递给 axios 获取请求。它适用于邮递员,但不适用于我的代码。我不知道我在哪里犯了错误。

我只想要来自 db 的一个特定数据,但我正在接收集合中可用的所有数据。但是有了邮递员,我得到了想要的数据

后端路线:

router.get('/displayUser', (req,res) => {
  const query = user =  req.body ;
  Services.find(query)
      .exec((err, services) => res.json(services))
})

axios 调用:我尝试了两种不同的方法,但都不起作用

方法一:

getData: async function () {
      const user = this.userId
      console.log(user) 
      let res = await axios.get('http://localhost:5000/api/services/displayUser' , { params: { user }})
      console.log(res.data);
}

方法二:

getData: async function () {
      var data = JSON.stringify({"user":this.userId});
      console.log(data)
      var config = {
        method: 'get',
        url: 'http://localhost:5000/api/services/displayUser',
        headers: { 
          'Content-Type': 'application/json'
        },
        data : data
      };

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});
}

当我在控制台中获取数据时,我得到了集合中可用的所有 3 个对象,而不是与用户 ID 相关的特定对象

截屏

但是在邮递员中它可以按要求工作

截屏

标签: mongodbvue.jsgetaxiospostman

解决方案


我这样做如下:

  • 当我需要得到时:
app.get('/detail/:id', function (req, res) {    
  //console.log(req.params.id);
  var url=urlDetail + "/" + req.params.id;
  axios.get(url)
  .then(function (response) {
   // result=response.data;
    res.render('database', { title: 'Detail' , dbs: response.data ,Version:pjson.version});
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
    //console.log("ici always");
  });
});
  • 当我需要发布时(req.body 是一个 json):
app.post('/carto/demande', function (req, res) {   
  let data; 
  console.log(req.params);
  console.log(req.body);
  var url=urlCartoDemande;

  axios.post(url,req.body)
  .then(function (response) {


    data=response.data;
    res.render('carto',    { title : 'Demande' ,Version:pjson.version,mode:"resultat",data:data   }    );
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed

  });      
});    

推荐阅读