Javascript 从 Axios API 返回数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48980380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:17:44  来源:igfitidea点击:

Returning data from Axios API

javascriptnode.jsrestaxios

提问by Bunkerguy

I am trying to use a Node.JS application to make and receive API requests. It does a get request to another server using Axios with data it receives from an API call it receives. The second snippet is when the script returns the data from the call in. It will actually take it and write to the console, but it won't send it back in the second API.

我正在尝试使用 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);
        });
}

...

...

axiosTestResult = axiosTest(); 
response.json({message: "Request received!", data: axiosTestResult});

I'm aware this is wrong, I'm just trying to find a way to make it work. The only way I can seem to get data out of it is through console.log, which isn't helpful in my situation.

我知道这是错误的,我只是想找到一种方法让它发挥作用。我似乎可以从中获取数据的唯一方法是通过 console.log,这对我的情况没有帮助。

回答by kingdaro

Return the promise from the axios call in the axiosTestfunction, then get the value out of the promise when calling it using another .then

axiosTest函数中的 axios 调用返回承诺,然后在使用另一个调用时从承诺中获取值.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 })
})

I'd also recommend reading up more on how promises work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

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

回答by Fahad_Shovon

I made an empty array before calling the axios get and after .then(function(response)) pushed the necessary data in the array at the end of the function returned the array

我在调用 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;
}   

回答by Arman Charan

axiosTest()is firing asynchronouslyand not being waited for.

axiosTest()正在射击asynchronously而不是等待。

A then()functionneeds to be hooked up afterwards in order to capture the responsevariable(axiosTestData).

then()function之后需要连接A以捕获responsevariable( axiosTestData)。

See Promisefor more info.

查看Promise更多信息。

See Asyncto level up.

Async升级。

// Dummy Url.
const url = 'https://jsonplaceholder.typicode.com/posts/1'

// Axios Test.
const axiosTest = axios.get

// Axios Test Data.
axiosTest(url).then(function(axiosTestResult) {
  console.log('response.JSON:', {
    message: 'Request received',
    data: axiosTestResult.data
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>

回答by Callum Dempsey Leach

The axios library creates a Promise() object. Promise is a built-in object in JavaScript ES6. When this object is instantiated using the new keyword, it takes a function as an argument. This single function in turn takes two arguments, each of which are also functions — resolve and reject.

axios 库创建了一个 Promise() 对象。Promise 是 JavaScript ES6 中的内置对象。当这个对象使用 new 关键字实例化时,它接受一个函数作为参数。这个单个函数又接受两个参数,每个参数也是函数——resolve 和 reject。

Promises execute the client side code and, due to coolJavascript asynchronous flow, could eventually resolve one or two things, that resolution (generally considered to be a semantically equivalent to a Promise's success), or that rejection (widely considered to be an erroneous resolution). For instance, we can hold a reference to some Promise object which comprises a function that will eventuallyreturn a response object (that would be contained in the Promise object). So one way we could use such a promise is wait for the promise to resolve to some kind of response.

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

You might raise we don't want to be waiting seconds or so for our API to return a call! We want our UI to be able to do things whilewaiting for the API response. Failing that we would have a very slow user interface. So how do we handle this problem?

您可能会说我们不想等待几秒钟左右的时间让我们的 API 返回调用!我们希望我们的 UI 能够等待 API 响应的同时做一些事情。否则,我们将拥有一个非常缓慢的用户界面。那么我们如何处理这个问题呢?

Well a Promise is asynchronous. In a standard implementation of engines responsible for executing Javascript code (such as Node, or the common browser) it will resolve in another process while we don't know in advance what the result of the promise will be. A usual strategy is to then sendour functions (i.e. a React setState function for a class) to the promise, resolved depending on some kind of condition (dependent on our choice of library). This will result in our local Javascript objects being updated based on promise resolution. So instead of getters and setters (in traditional OOP) you can think of functions that you might sendto your asynchronous methods.

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

I'll use Fetch in this example so you can try to understand what's going on in the promise and see if you can replicate my ideas within your axios code. Fetch is basically similarto axios without the innate JSON conversion, and has a different flow for resolving promises (which you should refer to the axios documentation to learn).

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

GetCache.js

获取缓存.js

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

Now we've written our GetCache method, lets see what it looks like to update a React component's state as an example...

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

Some React Component.jsx

一些 React Component.jsx

// Make sure you import GetCache from GetCache.js!

resolveData() {
    const { mySelection, date } = this.state; // We could also use props or pass to the function to acquire our selection and date.
    const setData = data => {
      this.setState({
        data: data,
        loading: false 
        // We could set loading to true and display a wee spinner 
        // while waiting for our response data, 
        // or rely on the local state of data being null.
      });
    };
  GetCache("mySelelection", date, setData);
  }

Ultimately, you don't "return" data as such, I mean you can but it's more idiomatic to change your way of thinking... Now we are sendingdata to asynchronous methods.

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

Happy Coding!

快乐编码!

回答by Yordan Georgiev

IMO extremely important rule of thumb for your client side js code is to keep separated the data handling and ui building logic into different funcs, which is also valid for axios data fetching ... in this way your control flow and error handlings will be much more simple and easier to manage, as it could be seen from this ok fetch

对于您的客户端 js 代码,IMO 极其重要的经验法则是将数据处理和 ui 构建逻辑分离到不同的函数中,这对于 axios 数据获取也有效......这样您的控制流和错误处理将很多更简单,更容易管理,从这个ok fetch可以看出

and this NOK fetch

和这个 NOK fetch

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>

       function getUrlParams (){
          var url_params = new URLSearchParams();
          if( window.location.toString().indexOf("?") != -1) {
             var href_part = window.location.search.split('?')[1]
             href_part.replace(/([^=&]+)=([^&]*)/g,
                function(m, key, value) {
                   var attr = decodeURIComponent(key)
                   var val = decodeURIComponent(value)
                   url_params.append(attr,val);
             });
          }
          // for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); }
          return url_params ;
       }


      function getServerData (url, urlParams ){
          if ( typeof url_params == "undefined" ) { urlParams = getUrlParams()  }
          return axios.get(url , { params: urlParams } )
          .then(response => {
             return response ;
          })
          .catch(function(error) {
             console.error ( error )
             return error.response;
          })
       }

    // Action !!!
    getServerData(url , url_params)
        .then( response => {
           if ( response.status === 204 ) {
              var warningMsg = response.statusText
              console.warn ( warningMsg )
              return
           } else if ( response.status === 404 || response.status === 400) {
              var errorMsg = response.statusText // + ": "  + response.data.msg // this is my api
              console.error( errorMsg )
              return ;
           } else {
              var data = response.data
              var dataType = (typeof data)
              if ( dataType === 'undefined' ) {
                 var msg = 'unexpected error occurred while fetching data !!!'
                 // pass here to the ui change method the msg aka
                 // showMyMsg ( msg , "error")
              } else {
                 var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from
                 // call here the ui building method
                 // BuildList ( items )
              }
              return
           }

        })




    </script>

回答by Fellow Stranger

You can use Async - Await:

您可以使用异步 - 等待:

async function axiosTest() {
  const response = await axios.get(url);
  const data = await response.json();  
}

回答by Paul

I know this post is old. But i have seen several attempts of guys trying to answer using async and await but getting it wrong. This should clear it up for any new references

我知道这个帖子很旧。但是我已经看到一些人尝试使用 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);
      }
    }

回答by Suvodeep Dubey

    async handleResponse(){
      const result = await this.axiosTest();
    }

    async axiosTest () {
    return await axios.get(url)
    .then(function (response) {
            console.log(response.data);
            return response.data;})
.catch(function (error) {
    console.log(error);
});
}

You can find check https://flaviocopes.com/axios/#post-requestsurl and find some relevant information in the GET section of this post.

您可以查看https://flaviocopes.com/axios/#post-requestsurl 并在本文的 GET 部分找到一些相关信息。