从Axios API返回数据

Bun*_*guy 33 javascript rest node.js axios

我正在尝试使用Node.JS应用程序来发出和接收API请求.它使用Axios向另一台服务器发送get请求,该请求包含从它接收的API调用接收的数据.第二个片段是脚本从调用中返回数据时.它实际上会接受并写入控制台,但它不会在第二个API中将其发回.

function axiosTest () {
axios.get(url)
.then(function (response) {
        console.log(response.data);
// I need this data here ^^
return response.data;
})
.catch(function (error) {
    console.log(error);
});
}
Run Code Online (Sandbox Code Playgroud)

...

axiosTestResult = axiosTest(); 
response.json({message: "Request received!", data: axiosTestResult});
Run Code Online (Sandbox Code Playgroud)

我知道这是错的,我只是想找到一种方法来使它工作.我似乎从中获取数据的唯一方法是通过console.log,这对我的情况没有帮助.

kin*_*aro 54

axiosTest函数中的axios调用返回promise ,然后在使用另一个调用它时从promise中获取值.then

function axiosTest() {
  return axios.get(url).then(response => {
    // returning the data here allows the caller to get it through another .then(...)
    return response.data
  })
}

axiosTest().then(data => {
  response.json({ message: 'Request received!', data })
})
Run Code Online (Sandbox Code Playgroud)

我还建议阅读有关promises如何工作的更多内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

  • 你是真正的 MVP @kingdaro 我多年来一直坚持我的代码然后我找到了你的答案,多么传奇 (3认同)
  • 如果函数axiosTest()与调用该函数位于单独的文件中,我似乎无法使它工作:axiosTest()。then ....在这种情况下有什么特别的事情吗? (2认同)

Mut*_*shi 12

我知道这个帖子很旧。但是我已经看到一些人尝试使用 async 和 await 来回答,但都弄错了。这应该清除任何新的参考

async function axiosTest() {
      try {
        const {data:response} = await axios.get(url) //use data destructuring to get data from the promise object
        return response
      }

      catch (error) {
        console.log(error);
      }
    }
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案 - 当您在应用程序中调试代码时,调用上述函数的函数以及链中的所有其他函数似乎都会返回,但稍后代码将在等待之后开始执行。您需要使应用程序中的所有函数异步,并使用await 调用所有函数。在 return 语句上放置一个断点,并在调用者的下一行代码上放置一个断点 - 一切都会变得清晰。 (2认同)

小智 7

我在调用axios get之前制作了一个空数组,然后在.then(function(response))在函数末尾将必要的数据推送到数组中后,返回了数组

function axiosTest () {
     var strr = [];
        axios.get(url)
       .then(function(response){
               strr.push(response.data);
        })


        .catch(function(error){
               console.log(error);
           });
        return strr;
}   
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@Fahad_Shovon!这花了我一天的时间进行故障排除,我使用您的解决方案解决了 (2认同)

Cal*_*ach 5

axios 库创建一个 Promise() 对象。Promise 是 JavaScript ES6 中的内置对象。当使用 new 关键字实例化该对象时,它采用一个函数作为参数。这个函数依次接受两个参数,每个参数也是函数 \xe2\x80\x94 解析和拒绝。

\n\n

Promise 执行客户端代码,并且由于很酷的Javascript 异步流程,最终可以解决一两个问题,即解决方案(通常被认为在语义上等同于 Promise 的成功)或拒绝(广泛认为是错误的决议)。例如,我们可以保存对某个 Promise 对象的引用,该对象包含一个最终返回响应对象(将包含在 Promise 对象中)的函数。因此,我们可以使用此类 Promise 的一种方法是等待 Promise 解析为某种响应

\n\n

您可能会说我们不想等待几秒钟左右让我们的 API 返回调用!我们希望 UI 能够在等待 API 响应时执行操作。如果做不到这一点,我们的用户界面将会非常慢。那么我们该如何处理这个问题呢?

\n\n

Promise 是异步的。在负责执行 Javascript 代码的引擎的标准实现中(例如 Node 或常见浏览器),它将在另一个进程中解析,而我们事先不知道 Promise 的结果是什么。通常的策略是将我们的函数(即类的 React setState 函数)发送到 Promise,并根据某种条件(取决于我们选择的库)进行解析。这将导致我们的本地 Javascript 对象根据承诺解析进行更新。因此,您可以考虑可以发送的函数,而不是 getter 和 setter(在传统的 OOP 中)给异步方法的函数,而不是 getter 和 setter(在传统的 OOP 中)。

\n\n

我将在此示例中使用 Fetch,以便您可以尝试了解 Promise 中发生的情况,并查看是否可以在您的 axios 代码中复制我的想法。Fetch基本上与 axios 类似,没有固有的 JSON 转换,并且具有不同的解析 Promise 的流程(您应该参考 axios 文档来了解)。

\n\n

获取缓存.js

\n\n
const base_endpoint = BaseEndpoint + "cache/";\n// Default function is going to take a selection, date, and a callback to execute.\n// We\'re going to call the base endpoint and selection string passed to the original function.\n// This will make our endpoint.\nexport default (selection, date, callback) => {  \n  fetch(base_endpoint + selection + "/" + date) \n     // If the response is not within a 500 (according to Fetch docs) our promise object\n     // will _eventually_ resolve to a response. \n    .then(res => {\n      // Lets check the status of the response to make sure it\'s good.\n      if (res.status >= 400 && res.status < 600) {\n        throw new Error("Bad response");\n      }\n      // Let\'s also check the headers to make sure that the server "reckons" its serving \n      //up json\n      if (!res.headers.get("content-type").includes("application/json")) {\n        throw new TypeError("Response not JSON");\n      }\n      return res.json();\n    })\n    // Fulfilling these conditions lets return the data. But how do we get it out of the promise? \n    .then(data => {\n      // Using the function we passed to our original function silly! Since we\'ve error \n      // handled above, we\'re ready to pass the response data as a callback.\n      callback(data);\n    })\n    // Fetch\'s promise will throw an error by default if the webserver returns a 500 \n    // response (as notified by the response code in the HTTP header). \n    .catch(err => console.error(err));\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在我们已经编写了 GetCache 方法,让我们看看更新 React 组件的状态作为示例......

\n\n

一些 React Component.jsx

\n\n
// Make sure you import GetCache from GetCache.js!\n\nresolveData() {\n    const { mySelection, date } = this.state; // We could also use props or pass to the function to acquire our selection and date.\n    const setData = data => {\n      this.setState({\n        data: data,\n        loading: false \n        // We could set loading to true and display a wee spinner \n        // while waiting for our response data, \n        // or rely on the local state of data being null.\n      });\n    };\n  GetCache("mySelelection", date, setData);\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

最终,您不会像这样“返回”数据,我的意思是您可以,但更惯用的做法是改变您的思维方式......现在我们将数据发送到异步方法。

\n\n

快乐编码!

\n