Returning data from Axios API

前端 未结 8 1294
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 11:52

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 rece

相关标签:
8条回答
  • 2020-12-07 12:55

    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

    and this 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>
    
    0 讨论(0)
  • 2020-12-07 12:58

    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 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);
          }
        }
    
    0 讨论(0)
提交回复
热议问题