【问题标题】:sending back api data to vue in express returns empty object在 express 中将 api 数据发送回 vue 返回空对象
【发布时间】:2020-04-25 06:02:16
【问题描述】:

我正在尝试使用我的 app.js 中的以下内容从我的 express 应用程序发回一些数据,这些数据来自第 3 方 api,我想将其发送回我的前端应用程序。我可以在我的 express api 中看到内容,但它似乎没有向我的前端提供结果??任何人都知道为什么我会在控制台下面显示日志。

我怀疑这与 express 应用的一些异步或超时问题有关,但我自己无法解决该问题。

function getFish(){
        axios.get('https://www.fishwatch.gov/api/species')
            .then(function (response) {
                console.log(response)
               return response

                })
                .catch(function (error) {
                    console.log(error);
                })
}


app.get('/getFish', async(req,res) =>{
    let fish = await getFish()
    res.json({fishes: fish})
})

当我尝试在我的应用中记录数据时,我只得到一个空对象

{}

这是我的 vue 代码,用于记录我的 express api 返回的值。

 created:function(){
     this.fetchFish()
   },

  methods: {

      fetchFish(){
         fetch('http://localhost:3000/getFish')
          .then((response) => {
             return response.json();
          })
          .then((data) => {
          console.log(data);
        });
    }
  }

【问题讨论】:

    标签: express vue.js


    【解决方案1】:

    您需要在服务器的 getFish 函数中返回 axios 承诺,否则 /getFish 路由不会是 awaiting 任何东西:

    function getFish(){
        // New `return` statement
        return axios.get('https://www.fishwatch.gov/api/species')
        .then(function (response) {
            console.log(response)
            return response
        })
        .catch(function (error) {
            console.log(error);
        })
    }
    

    【讨论】:

    • 是的,这对我有用,我现在可以在我的 getFish 路由中看到数据 :) 我从未使用过 axios,但我无法在后端使用 fetch,所以感谢您帮助我
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多