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;
                return res;
        } else{
            console.error('Error. Status code: '+ response.status + ' '+ response.statusText);
            return {message: 'Failed'};
        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(){
            const res = getMethod();
            console.log("Get Information");

        const classifyInfo = function(data){
            const ul=document.getElementsByTagName('section')[1].getElementsByTagName('ul');
            let content='';
                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++){

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

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 πŸ˜‰

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

  1. Hi there I am so glad I found your website, I really found you by accident, while I was browsing on Askjeeve for something else, Anyways I am here
    now and would just like to say thanks a lot for a incredible post and a
    all round thrilling blog (I also love the theme/design),
    I donΒ’t have time to browse it all at the moment but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read a lot more, Please do
    keep up the awesome work.


Leave a Comment