【问题标题】:Axios get request with parameter is not working带有参数的axios获取请求不起作用
【发布时间】:2021-02-26 21:20:59
【问题描述】:

我正在向 axios get 请求传递一个参数。它适用于邮递员,但不适用于我的代码。我不知道我在哪里犯了错误。

我只想要一个来自 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 相关的特定对象

Screenshot

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

screenshot

【问题讨论】:

  • 尝试将数据发送到 axios 而不对其进行字符串化(即) var data = {"user":this.userId};
  • 我试过了,还是不行@AmaarshallYaswankar
  • Ayyo,这让我很困惑 :( @Jayashree
  • 我也一直为此头疼:'(@AmaarshallYaswankar
  • 很少见的场景哈哈

标签: mongodb vue.js get axios postman


【解决方案1】:

我这样做如下:

  • 当我需要获取时:
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

  });      
});    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2021-09-19
    • 1970-01-01
    • 2021-03-31
    • 2018-05-20
    相关资源
    最近更新 更多