Calling to Rest function from attached script returns undefined instead of data

I am doing a Rest API in javascript for improving myself and having a little of fun…
And the API works well!

const getMethod = function(reqType){
    let req;
    if(!reqType){
        req=server+":"+port;
    }
    else{
        req=`${server}:${port}/${reqType}`;
    }
    fetch(req,{mode:'cors'})
    .then(response=>{
        if(response.ok===true){
            response.json().then(res=>{
                console.log(res);
                return res;
            }).catch(err=>console.error(err));
        } else{
            console.error('Error. Status code: '+ response.status + ' '+ response.statusText);
            return {message: 'Failed'};
        }
    })
    .catch(err=>{console.error(err);
        return {message: 'Failed'}
    });
}

I know it can be improved, but for now it works. console.log(res) actually shows an Array of Mock Data from Express server.

The thing is that, in order to avoid creating another server, I attached into the HTML the following code:

<script type="text/javascript">
        window.onload = function(){
            console.log(getMethod());
            const res = getMethod();
            console.log(res);
            classifyInfo(res);
            console.log("Get Information");
        }

        const classifyInfo = function(data){
            const ul=document.getElementsByTagName('section')[1].getElementsByTagName('ul');
            let content='';
            if(data['peliculas']&&data['clasificaciones']){
                const movies=data['peliculas'];
                const classes=data['clasificaciones'];
                for(let i=0;i<classes.length;i++){
                    const clasMovies = searchInfo(movies, classes[i].nombre);
                    content+=`<li>${classes[i].nombre} <ul>`;
                    for(let j=0;j<clasMovies;j++){
                        content+=`<li>${clasMovies[j].nombre}</li>`;
                    }
                    content+='</ul></li>';
                }
            }
        }

        const searchInfo = function(data, term){
            const returnElement = data.filter(el=>el['clasificacion']==term);
            return returnElement;
        }
    </script>

At onload function, res becomes undefined even if afterwards the console shows the array. However, I don’t know why it is doing this.

I have tried to use await for waiting the response, but that does not work either.

Any ideas would be appreciated 😉

39 thoughts on “Calling to Rest function from attached script returns undefined instead of data”

  1. Well… It was easier than I thought…

    I suppose that I should just surround asynchronous await order with some try/catch just in case…

    I modified my API like this:

    const getMethod = async function(reqType){
        let req;
        if(!reqType){
            req=server+":"+port;
        }
        else{
            req=`${server}:${port}/${reqType}`;
        }
        const response = await fetch(req,{mode:'cors'})
    
        return response.json();
    }
    

    Which returns a Promise and then I modified the script at my html like this:

            window.onload = async function(){
                const res = await getMethod();
                console.log(res);
                classifyInfo(res);
                console.log("Get Information");
            }
    

    resolving the promise and getting my good, coming-from-node-server, data.

    I like to use resolve, reject, but I suppose a try/catch will do the same.

    Reply
  2. community bible church give community america foundation , xeric environments. positive feedback process side effects of lyrica lyrica dosage , followers bot roblox community health center middletown ct covid testing community in biology meaning , positive reinforcement definition community biology 101 references? community colleges near me online community acquired pneumonia nursing diagnosis, community theatre definition planning process business management.
    community action partnership round lake beach il , community bank definition community bridges santa cruz community outing synonym.

    Reply
  3. the radeon software adrenalin 2020 edition 20.3.1 drawing program website to buy Autocad free open source office software for mac. back office software free download office software ubuntu engeeeneringu#$sssaunnplus , 1506g new software 2020 download. office software fГјr mac kaufen, 2020 software development trends 2020 design software coupon code medical office software programs. ms office 2010 software free download utorrent office software courses, office software for mac.

    Reply
  4. pharmacie bordeaux centre ville therapie de couple montreal difference between pregabalin and gabapentin , pharmacie auchan st priest act therapy borderline . pharmacie beauvais la seguiniere therapie miroir , pharmacie auchan ales pharmacie beaulieu saint etienne act therapy steven hayes pharmacie beaute angers . pharmacie leclerc toul traitement diabete type 2 , therapies humanistes definition pharmacie bordeaux pey berland . pharmacie annecy garde pharmacie ouverte paris 15 , xeracalm pharmacie lafayette pharmacie annecy le vieux pommaries act therapy russ harris therapie de couple remboursee . pharmacie brest saint martin pharmacie beaulieu place de champagne chГўteauroux , pharmacie obernai medicaments diuretiques . pharmacie de garde marseille 13005 pharmacie leclerc plerin , therapie comportementale et cognitive doctolib pharmacie des ormeaux aix en provence therapie de couple bruxelles pharmacie avignon tgv .

    Reply

Leave a Comment