【问题标题】:How to retrieve axios data from the promise如何从 Promise 中检索 axios 数据
【发布时间】:2019-04-22 21:24:50
【问题描述】:

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

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

【问题讨论】:

  • 我怀疑您的代码缺少处理拒绝的 catch 块。另外,我没有看到 Paramus 被传入。
  • 您是否尝试过在 promise 上实现 catch 回调?您可能在后端有错误。
  • 也许您在 HTTP 下使用节点并且您正在获取 CORS,因为 axios 正在尝试获取 HTTPS。尝试放置拒绝功能和/或更改 URL 以确保 axios 代码正常工作(我也看不出有什么问题)。
  • 抱歉。我只是注意到,即使链接断开,我也会得到响应。但是为什么我会用邮递员得到预期的对象呢?

标签: javascript node.js json axios


【解决方案1】:

你需要像这样调用承诺:

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

【讨论】:

    【解决方案2】:

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

    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 })
          })
    

    这里有与您类似的问题:Returning data from Axios API ||也请检查一下。

    【讨论】:

    • 第二次调用,你传递数据并返回 response.json ?还是 response.data.json ?
    • 只是 response.json 而已。请尝试一下:)
    • 它说响应是未定义的,因为我认为你没有将它传递给函数调用
    • 能否请您在第二个函数中使用 consol.log(data)?
    • 我在代码中添加了一个catch,所以它会在这里捕获错误,以便我可以更好地检查它。并告知结果
    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2019-03-14
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多