"Cross origin requests are only supported for HTTP." error when loading a local file
Asked Answered
A

30

1038

I'm trying to load a 3D model, stored locally on my computer, into Three.js with JSONLoader, and that 3D model is in the same directory as the entire website.

I'm getting the "Cross origin requests are only supported for HTTP." error, but I don't know what's causing it nor how to fix it.

Aboveboard answered 25/5, 2012 at 9:41 Comment(8)
Are you trying to do this locally?Rudolfrudolfo
You need to use localhost, even if its local fileFoolscap
because of cross domain policyFrailty
But it sin't cross domain!Aboveboard
If you're using Chrome, starting it from the terminal with the --allow-file-access-from-files option might help you out.Lenni
Yeah, it's not really cross-domain when the file is in the same folder as the webpage, now is it... I found that if you use Firefox instead of Chrome, the problem goes away.Variegation
I just added http:// before the URL and it workedLiard
"if you use Firefox instead of Chrome, the problem goes away". Alas, no longer true - Firefox explicitly treats it the same as Chrome :-(Virgenvirgie
F
940

My crystal ball says that you are loading the model using either file:// or C:/, which stays true to the error message as they are not http://

So you can either install a webserver in your local PC or upload the model somewhere else and use jsonp and change the url to http://example.com/path/to/model

Origin is defined in RFC-6454 as

   ...they have the same
   scheme, host, and port.  (See Section 4 for full details.)

So even though your file originates from the same host (localhost), but as long as the scheme is different (http / file), they are treated as different origin.

Firebrick answered 25/5, 2012 at 9:42 Comment(15)
Yeah, I'm trying to do this using file://, but I don't understand why this is permitted. Well, I'm installing Lampp I guess...Aboveboard
Imagine if that is allowed and a webapp whereby the author of the page uses something like load('file://C:/users/user/supersecret.doc') and then upload the content to their server using ajax etc.Firebrick
But I'm trying to load something from my own directory, even index.html is located there!Aboveboard
unfortunately, policy is made for all cases, not only for yours :(, so ya gotta bear with itFirebrick
You may also use the --allow-file-access-from-files switch in chrome. Per my answer here: #8450216Organization
@edwardtyl the browser is just displaying whatever html returned by the server and by no means is running any executable beyond that is returned (i.e. it doesn't even know what language the server is running). Do you have any documentation that backs up your statement? I'm interested.Firebrick
Oh, wait that's not what I meant to say. sorry! xD What I meant to say is that if you're running PHP on a computer, then PHP has access to all the files of the computer it is running on, while javascript will not because it will try to access the client's files (security risk) instead of the server's. This is why when you want to load a file on your server e.g. C:/hi.txt you will be able to load it through PHP (runs on the server where the file is) but not through javascript (runs on the client, which is probably a different computer).Denverdeny
So for this situation ajax would be the solution.Denverdeny
@AndreasWong Imagine if the page in question is loaded from file:// though, then your example is irrelevant and (like the OP and myself are saying), it's not a cross-domain issue because the domain is effectively localhost implicitly because of file://Gardol
use script tag with id is better than creating server.Hectometer
Where can I find a crystal ball like yours? It would help me a lot in my daily programming endeavours.Pricilla
I'm getting this error, I'm not running from file://. I'm on localhost:8001 trying to load rtmp:// stream from localhost.Manhood
@Gardol thanks, it's actually a good question. I have edited my answer.Firebrick
@Aboveboard I have updated my answer to address your question about originFirebrick
I realize this is very old and I'm sure my comment is unlikely to ever be seen, however. I find it odd and inconsistent that an html file being loaded as file:///path/htmlfile.html is considered to be served as http while a javascript file served with a relative path is not. This is technically incorrect. They are the same. Both are served as file:/// ... so CORS seems in error.Snapper
D
796

Just to be explicit - Yes, the error is saying you cannot point your browser directly at file://some/path/some.html

Here are some options to quickly spin up a local web server to let your browser render local files

Python

If you have Python installed...

  1. Change directory into the folder where your file some.html or file(s) exists using the command cd /path/to/your/folder

  2. Start up a Python web server using one of below commands

    python -m SimpleHTTPServer # python 2

    python3 -m http.server # python 3

This will start a web server to host your entire directory listing at http://localhost:8000

  1. You can use a custom port python3 -m http.server 9000 giving you link: http://localhost:9000 to point your browser at

This approach is built in to any Python installation.

VSCode

If you are using Visual Studio Code you can install the Live Server extension which provides a local web server ... after installing this extension click on Go Live widget on bottom of vscode window to launch browser pointing at your code dir

Node.js

Alternatively, if you demand a more responsive setup and already use nodejs...

  1. Install http-server by typing npm install -g http-server

  2. Change into your working directory, where yoursome.html lives

  3. Start your http server by issuing http-server -c-1

This spins up a Node.js httpd which serves the files in your directory as static files accessible from http://localhost:8080

Ruby

If your preferred language is Ruby ... the Ruby Gods say this works as well:

ruby -run -e httpd . -p 8080

PHP

Of course PHP also has its solution.

php -S localhost:8000
Dispenser answered 6/2, 2014 at 16:36 Comment(14)
This saved me a ton of time thanks. My Python install didnt have the SimpleHTTPServer module but the node instructions worked like a charm.Juror
In response to LukeP's comment, in python 2.7 the command does work as per the instructions $ python -m SimpleHTTPServer, which produces the message: Serving HTTP on 0.0.0.0 port 8000 ... If you spell the module name wrong, e.g. $ python -m SimpleHttpServer then you will get the error message No module named SimpleHttpServer You will get a similar error message if you have python3 installed (v. python 2.7). You can check your version of python using the command: $ python --version. You can also specify the port to listen on like this: $ python -m SimpleHTTPServer 3333Saire
The python server serves up files from the directory where you start the server. So if the files you want to serve up are located in /Users/7stud/angular_projects/1app, then start the server in that directory, e.g. $ cd ~/angular_projects/1app, then $ python -m SimpleHTTPServer. In your browser enter the url http://localhost:8000/index.html. You can also request files in subdirectories of the directory where you started the server, e.g. http://localhost:8000/subdir/hello.htmlSaire
If you have ruby installed, you can start up a server with this command: $ ruby -run -e httpd . -p 5000 (serves files out of the current dir (.) on port 5000)Saire
If you have nodejs installed, you can download an http server: 1) Change directories to the directory where you want to serve files from: $ cd ~/angular_projects/1app 2) If you are using nvm: $ nvm use 0.10 (specifies the version of nodejs to activate) 3) Download and install the server as a command line command: npm install http-server -g 4) Run the server: $ http-server ., which will produce the message Starting up http-server, serving . on: http://0.0.0.0:8080. That allows you to use urls in your browser like localhost:8080/index.html.Saire
I've heard that Python is simple and powerful, just like "X" language, but this is ridiculous! No need to install XAMPP, or setup a simple http server js with node to serve static files - One command and boom! Thank you very much, saves a LOT of time and hassle.Wilder
AWESOME! - for Python on Windows use: python -m http.server 8080 ...or whatever port you want and when you want to quit it just ctrl-c.Prostatectomy
You might want to be aware that python (at least python 2's) SimpleHTTPServer is extremely slow. So slow that it's often useless for projects that load lots of images or do audio or video. Hence this question about alternativesThriller
In my case to be able to run POST requests with .js python was throwing 501, went with node.Sciomancy
Worked for me! I was unable to add my local json files to my leaflet map via the leaflet-ajax plugin due to the CORS policy in Chrome. I did your Python 3 solution and the layer is showing up now. Thank you!Loewe
@Scott Stensland: Regarding your Node.js option, after issuing http-server -c-1 to start the http server, what command do I issue to stop it later?Butyrin
@Butyrin the command is sync so just hit control + c in same terminal to kill that processDispenser
@Scott Stensland: It's such a blessing to work with Node http-server smoothly. Thanks for the share. Just one thing I'd like to know, is there any tutorial available to learn more about the commands to work with http-server and manipulate its settings? I found http-server quite interesting and want to delve deeper into it, apart from starting and stopping it. So, if you can help with some tutorial/documentation links?Butyrin
@Butyrin typically any nodejs package is installed and managed using the tool called npm ... just google ... npm http-server ... or in general npm some-package .... the npmjs.com site has a rundown on the given package details like usage as well as its repo where its source code lives ... once installed issue ... http-server --help to display usage parameters ... these tricks follow a pattern also used by most software so when you distribute you own code you too will bake in such offerings ... welcome to open sourceDispenser
L
197

In Chrome you can use this flag:

--allow-file-access-from-files

Read more here: How to launch html using Chrome at "--allow-file-access-from-files" mode?

Litton answered 20/5, 2014 at 11:36 Comment(5)
@Blairg23, keep in mind that this solution requires restarting all instances of Chrome.exe for it to workThickhead
Please, explain how to use it in chrome.Simarouba
@Priya Should not do this thoughCalysta
I would suggest using Chromium only for local debugging (starting it with flag --allow-file-access-from-files). It means using Chrome for common web browsing, and use Chromium as the default application for HTML file.Boast
Note that fetch() still denies this anyway. You must use XMLHttpRequest in some mannerLenee
A
74

Ran in to this today.

I wrote some code that looked like this:

app.controller('ctrlr', function($scope, $http){
    $http.get('localhost:3000').success(function(data) {
        $scope.stuff = data;
    });
});

...but it should've looked like this:

app.controller('ctrlr', function($scope, $http){
    $http.get('http://localhost:3000').success(function(data) {
        $scope.stuff = data;
    });
});

The only difference was the lack of http:// in the second snippet of code.

Just wanted to put that out there in case there are others with a similar issue.

Abuse answered 20/2, 2014 at 16:27 Comment(0)
S
50

Just change the url to http://localhost instead of localhost. If you open the html file from local, you should create a local server to serve that html file, the simplest way is using Web Server for Chrome. That will fix the issue.

Salba answered 16/12, 2016 at 3:1 Comment(2)
+1 for Web Server for Chrome app link - it's by far the simplest & cleanest solution for temporary httpd setup for Chrome IMOManwell
It saved me. The exact solutionGastrulation
Q
37

I'm going to list 3 different approaches to solve this issue:

  1. Using a very lightweight npm package: Install live-server using npm install -g live-server. Then, go to that directory open the terminal and type live-server and hit enter, page will be served at localhost:8080. BONUS: It also supports hot reloading by default.
  2. Using a lightweight Google Chrome app developed by Google: Install the app, then go to the apps tab in Chrome and open the app. In the app point it to the right folder. Your page will be served!
  3. Modifying Chrome shortcut in windows: Create a Chrome browser's shortcut. Right-click on the icon and open properties. In properties, edit target to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/ChromeDevSession" and save. Then using Chrome open the page using ctrl+o. NOTE: Do NOT use this shortcut for regular browsing.

Note: Use http:// like http://localhost:8080 in case you face error.

Quintonquintuple answered 29/11, 2017 at 6:54 Comment(0)
M
24

Use http:// or https:// to create url

error: localhost:8080

solution: http://localhost:8080

Microscopium answered 12/10, 2018 at 3:11 Comment(2)
Exactly same issue. I didn't know I was using without http:Alba
omg i was looking for the sollution in 3 hours thanksKavanaugh
P
22

In an Android app — for example, to allow JavaScript to have access to assets via file:///android_asset/ — use setAllowFileAccessFromFileURLs(true) on the WebSettings that you get from calling getSettings() on the WebView.

Pettit answered 29/12, 2016 at 22:15 Comment(1)
Brilliant! We were just about to rewrite methods to inject JSON into variables .. but this works! webView.getSettings().setAllowFileAccessFromFileURLs(true);Codling
W
19

fastest way for me was: for windows users run your file on Firefox problem solved, or if you want to use chrome easiest way for me was to install Python 3 then from command prompt run command python -m http.server then go to http://localhost:8000/ then navigate to your files

python -m http.server
Windblown answered 1/10, 2018 at 3:55 Comment(0)
M
14

Easy solution for whom using VS Code

I've been getting this error for a while. Most of the answers works. But I found a different solution. If you don't want to deal with node.js or any other solution in here and you are working with an HTML file (calling functions from another js file or fetch json api's) try to use Live Server extension.

It allows you to open a live server easily. And because of it creates localhost server, the problem is resolving. You can simply start the localhost by open a HTML file and right-click on the editor and click on Open with Live Server.

It basically load the files using http://localhost/index.html instead of using file://....

EDIT

It is not necessary to have a .html file. You can start the Live Server with shortcuts.

Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server. [On MAC, cmd+L, cmd+O and cmd+L, cmd+C]

Hope it will help someone :)

Meggs answered 9/10, 2019 at 21:16 Comment(0)
S
13

For those on Windows without Python or Node.js, there is still a lightweight solution: Mongoose.

All you do is drag the executable to wherever the root of the server should be, and run it. An icon will appear in the taskbar and it'll navigate to the server in the default browser.

Also, Z-WAMP is a 100% portable WAMP that runs in a single folder, it's awesome. That's an option if you need a quick PHP and MySQL server. Though it hasn't been updated since 2013. A modern alternative would be Laragon or WinNMP. I haven't tested them, but they are portable and worth mentioning.

Also, if you only want the absolute basics (HTML+JS), here's a tiny PowerShell script that doesn't need anything to be installed or downloaded:

$Srv = New-Object Net.HttpListener;
$Srv.Prefixes.Add("http://localhost:8080/");
$Srv.Start();
Start-Process "http://localhost:8080/index.html";
While($Srv.IsListening) {
    $Ctx = $Srv.GetContext();
    $Buf = [System.IO.File]::OpenRead((Join-Path $Pwd($Ctx.Request.RawUrl)));
    $Ctx.Response.ContentLength64 = $Buf.Length;
    $Ctx.Response.Headers.Add("Content-Type", "text/html");
    $Buf.CopyTo($Ctx.Response.OutputStream);
    $Buf.Close();
    $Ctx.Response.Close();
};

This method is very barebones, it cannot show directories or other fancy stuff. But it handles these CORS errors just fine.

Save the script as server.ps1 and run in the root of your project. It will launch index.html in the directory it is placed in.

Sonnysonobuoy answered 4/3, 2015 at 5:24 Comment(2)
If you install php or you have installed, you can start a server in your folder: php.net/manual/es/features.commandline.webserver.phpGraber
@Graber That manual is in Spanish!Sheasheaf
B
12

If you use old version of Mozilla Firefox (pre-2019), it will work as expected without any issues;

P.S. Surprisingly, old versions of Internet Explorer & Edge work absolutely fine too.

Buckskins answered 2/4, 2018 at 17:0 Comment(1)
not anymore. firefox and ie are both blocking cors request for me.Sortilege
D
9

I suspect it's already mentioned in some of the answers, but I'll slightly modify this to have complete working answer (easier to find and use).

  1. Go to: https://nodejs.org/en/download/. Install nodejs.

  2. Install http-server by running command from command prompt npm install -g http-server.

  3. Change into your working directory, where index.html/yoursome.html resides.

  4. Start your http server by running command http-server -c-1

Open web browser to http://localhost:8080 or http://localhost:8080/yoursome.html - depending on your html filename.

Dang answered 28/8, 2018 at 16:7 Comment(2)
After running the command http-server -c-1 to start the http server, what command do I issue to stop it later without closing the command prompt?Butyrin
npx http-server [index.html folder] . No global install needed but upvote for http-server being simple and straightforward.Soidisant
M
5

I was getting this exact error when loading an HTML file on the browser that was using a json file from the local directory. In my case, I was able to solve this by creating a simple node server that allowed to server static content. I left the code for this at this other answer.

Micamicaela answered 10/11, 2014 at 14:14 Comment(0)
F
3

It simply says that the application should be run on a web server. I had the same problem with chrome, I started tomcat and moved my application there, and it worked.

Futurity answered 13/10, 2016 at 16:6 Comment(0)
K
3

I suggest you use a mini-server to run these kind of applications on localhost (if you are not using some inbuilt server).

Here's one that is very simple to setup and run:

https://www.npmjs.com/package/tiny-server
Kabyle answered 21/8, 2017 at 11:15 Comment(0)
P
3

Not possible to load static local files(eg:svg) without server. If you have NPM /YARN installed in your machine, you can setup simple http server using "http-server"

npm install http-server -g
http-server [path] [options]

Or open terminal in that project folder and type "hs". It will automaticaly start HTTP live server.

Prefer answered 26/6, 2018 at 5:54 Comment(1)
duplicate answerDispenser
W
3

Experienced this when I downloaded a page for offline view.

I just had to remove the integrity="*****" and crossorigin="anonymous" attributes from all <link> and <script> tags

Waiwaif answered 12/4, 2020 at 7:31 Comment(1)
I don't understand the downvoting for this answer, it does solve the issue for me in Chrome.Kentiga
P
3

If you insist on running the .html file locally and not serving it with a webserver, you can prevent those cross origin requests from happening in the first place by making the problematic resources available inline.

I had this problem when trying to to serve .js files through file://. My solution was to update my build script to replace <script src="..."> tags with <script>...</script>. Here's a gulp approach for doing that:

1. run npm install --save-dev to packages gulp, gulp-inline and del.

2. After creating a gulpfile.js to the root directory, add the following code (just change the file paths for whatever suits you):

let gulp = require('gulp');
let inline = require('gulp-inline');
let del = require('del');

gulp.task('inline', function (done) {
    gulp.src('dist/index.html')
    .pipe(inline({
        base: 'dist/',
        disabledTypes: 'css, svg, img'
    }))
    .pipe(gulp.dest('dist/').on('finish', function(){
        done()
    }));
});

gulp.task('clean', function (done) {
    del(['dist/*.js'])
    done()
});

gulp.task('bundle-for-local', gulp.series('inline', 'clean'))
  1. Either run gulp bundle-for-local or update your build script to run it automatically.

You can see the detailed problem and solution for my case here.

Plexus answered 4/5, 2020 at 15:38 Comment(0)
Q
2

For all y'all on MacOS... setup a simple LaunchAgent to enable these glamorous capabilities in your own copy of Chrome...

Save a plist, named whatever (launch.chrome.dev.mode.plist, for example) in ~/Library/LaunchAgents with similar content to...

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>launch.chrome.dev.mode</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Applications/Google Chrome.app/Contents/MacOS/Google Chrome</string>
        <string>-allow-file-access-from-files</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

It should launch at startup.. but you can force it to do so at any time with the terminal command

launchctl load -w ~/Library/LaunchAgents/launch.chrome.dev.mode.plist

TADA! 😎 💁🏻 🙊 🙏🏾

Quintero answered 5/7, 2016 at 0:37 Comment(1)
Thanks, @Alex Gray. your method works for me. Can it be used for other browsers? If so, how can I do it? I tried it with Brave Browser, it did not work.Awfully
M
1

er. I just found some official words "Attempting to load unbuilt, remote AMD modules that use the dojo/text plugin will fail due to cross-origin security restrictions. (Built versions of AMD modules are unaffected because the calls to dojo/text are eliminated by the build system.)" https://dojotoolkit.org/documentation/tutorials/1.10/cdn/

Myles answered 7/9, 2015 at 10:8 Comment(0)
B
1

One way it worked loading local files is using them with in the project folder instead of outside your project folder. Create one folder under your project example files similar to the way we create for images and replace the section where using complete local path other than project path and use relative url of file under project folder . It worked for me

Belch answered 8/6, 2016 at 3:16 Comment(0)
C
1
  • Install local webserver for java e.g Tomcat,for php you can use lamp etc
  • Drop the json file in the public accessible app server directory
  • List item

  • Start the app server,and you should be able to access the file from localhost

Confirm answered 8/6, 2018 at 11:5 Comment(0)
S
1

For Linux Python users:

import webbrowser
browser = webbrowser.get('google-chrome --allow-file-access-from-files %s')
browser.open(url)
Shaduf answered 4/5, 2020 at 13:51 Comment(3)
Is there no reason why google-chrome --allow-file-access-from-files <url> wouldn't work and be more concise?Spaceless
@Spaceless The webbrowser module have arguments that enable you different kinds of "opening" eg. open in current tab, new tab, new window etc.Shaduf
can the url be a file path?Decongestant
R
0

Many problem for this, with my problem is missing '/' example: jquery-1.10.2.js:8720 XMLHttpRequest cannot load http://localhost:xxxProduct/getList_tagLabels/ It's must be: http://localhost:xxx/Product/getList_tagLabels/

I hope this help for who meet this problem.

Requite answered 12/7, 2016 at 5:31 Comment(0)
A
0

I have also been able to recreate this error message when using an anchor tag with the following href:

<a href="javascript:">Example a tag</a>

In my case an a tag was being used to get the 'Pointer Cursor' and the event was actually controlled by some jQuery on click event. I removed the href and added a class that applies:

cursor:pointer;
Aggappera answered 11/6, 2018 at 14:18 Comment(0)
M
0

cordova achieve this. I still can not figure out how cordova did. It does not even go through shouldInterceptRequest.

Later I found out that the key to load any file from local is: myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

And when you want to access any http resource, the webview will do checking with OPTIONS method, which you can grant the access through WebViewClient.shouldInterceptRequest by return a response, and for the following GET/POST method, you can just return null.

Matchmaker answered 14/12, 2019 at 15:51 Comment(0)
R
0

If you are searching for a solution for Firebase Hosting, you can run the

firebase serve --only hosting command from the Firebase CLI

That's what I came here for, so I thought I'd just leave it here to help like ones.

Rolle answered 26/10, 2021 at 5:59 Comment(0)
P
0

If your using VS code just trying loading a live server in there. fixed my problem immediately.

Padua answered 30/10, 2021 at 21:48 Comment(0)
P
0

url should be like:

 createUserURL = "http://www.localhost:3000/api/angular/users"

instead of:

 createUserURL = "localhost:3000/api/angular/users"
Paphian answered 21/11, 2022 at 4:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.