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 😉

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

Leave a Comment