简体   繁体   中英

Need ideas for using axios when running html file locally (e.g. file:// path in browser)

The goal is to have a .html file that can be opened directly (eg run as file://path-to-file.../file.html in Chrome browser).

Their is a /user-json folder, where users can drop in their own .json files and the .html file loads up the json data.

I am currently using axios to a) find all files in that /user-json directory, and then b) load them in for use in the javascript.

The issue is that CORS/Browsers blocks these axios requests due to security policies.

A work around is to use --allow-file-access-from-files, but I want to provide an easy way for anyone to just drop-in their own "user-json" data into that /user-json folder, and have the .html detect and load it up, without needing to play around with their chrome browser settings or even running a web server.

Any ideas for getting this to work or alternative methods? Please don't suggest running the files on a server as I'm away of that option - I'm looking for a way users can provide their own files that the locally opened .html file can detect and load in.

There are many ways you can go about this. It's mostly a matter of picking your favourite abstraction.

Easiest would be to leverage a service like CORS Anywhere . Though of course that isn't the most robust solution, and if you're concerned with the aesthetics of your code, it likely won't appeal (note: there is an NPM package ).

Alternatively, if you want to host your own solution, you can spin up a free instance, like a Cloudflare Worker ; they even have an example of how to accomplish what you're after here .

Passing your requests through nginx is also possible, and arguably much more succinct and performant.

Any way you go about it, you'll have to route your requests through some kind of proxy, because a stock Chrome browser is not gonna cut it.

Bon voyage.

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