提问者:小点点

如何从promise中检索axios数据


我目前正在尝试使用axios查询我的后端,并使用res.json向特定地址发送一个对象,我也可以使用postaman查看它。但是当试图构建一个函数来检索它时,我的对象看起来像:Promise{pending}。如何重构函数?

   isAuthenticated = () => {
        return axios.get('https://myaddress/authenticate')
            .then(function (response) {
                return response.data
            })
    };

共2个答案

匿名用户

你需要这样称呼这个promise:

isAuthenticated().then(result => console.log(result))
.catch(error => console.log(error));

匿名用户

使用此代码,如果仍然遇到问题,请告诉我。

const isAuthenticated = () => { 
        return axios.get('https://myaddress/authenticate').then(response => {
            // returning the data here allows the caller to get it through another .then(...)
            return response.data
          }).catch(error => console.log(error));
     };

     isAuthenticated().then(data => {
        response.json({ message: 'Request received!', data })
      })

这里有和你类似的问题:从 Axios API ||返回数据也请检查一下。