简体   繁体   中英

My code runs offline with console.log but not in browser

So I am working on my first project and I am only figuring things out as I go. I am using an npm module called mal-scraper which gathers data(such as: titles, links for the anime and pictures) from MyAnimeList website and want to create a website which displays currently airing shows using this module.

I ran the code offline and saved it to a variable. It printed out the desired results when called, then I wanted to make cards like so:

let count = Object.keys(obj).length;
        //iterate through the obj and create cards
        for (let i= 0;i < count;i++) {
            html += `<div class="column">
            <div class="card">
                <div class="container">
                        <a id="link" href= "${obj[i]['link']}"><img id="img" src="${obj[i]['picture']}"></a>
                        <h1 id="title" >${obj[i]['title']}</h1>
                        <p id="date">${obj[i]['releaseDate']}</p>
                </div>
            </div>
        </div>`
        }
        console.log(html); //test
        return html;

This works fine too, but when I try adding it to the index.html with jquery

$("#row").add(html) 

It does not work and I get an error of Cross-Origin something which I don't understand and a CORB warning of sorts. I managed to fix the first with a chrome extension but have no idea how to fix the latter.

Hello and welcome to StackOverflow :)

You may need to fetch the information from an custom backend and set the according headers.

If you dont know how to write a custom backend or just try to play around with it you can use https://cors-anywhere.herokuapp.com/ . It tunnels the original requests and adds the headers to allow cross origin request.

The basic idea behind CORS is to prevent other websites request resources from your server without your permission.

More information about it here: https://developer.mozilla.org/de/docs/Web/HTTP/CORS .

Sure this is a bit old but since it apperas first in G Search for "...javascript not working offline" here is an obvious yet easy to miss detail.

Using <script>...</script> with just the open close tags bare will not garner results. An offline browser is not as smart as some engines which may be running dependency handlers in the background of online servers.

Simply add <script type="text/javascript">...</script> to get native support of your browser.

Stick with type=javascript for better offline compatibility, even though most engine talk references using text/application type.

Tested w/ Chrome, FF Beta on Android Lollipop; as local file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM