[javascript] "Cross origin requests are only supported for HTTP." error when loading a local file

I'm trying to load a 3D model 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.

This question is related to javascript file http three.js cors

The answer is


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.


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.


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

In Chrome you can use this flag:

--allow-file-access-from-files

Read more here.


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.


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.


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 2

If you have Python installed...

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

  2. Start up a Python web server using the command python -m SimpleHTTPServer

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

  1. You can use a custom port python -m SimpleHTTPServer 9000 giving you link: http://localhost:9000

This approach is built in to any Python installation.

Python 3

Do the same steps, but use the following command instead python3 -m http.server

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

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.


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 :)


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.


  • 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


If you use Mozilla Firefox, It will work as expected without any issues;

P.S. Surprisingly, IntenetExplorer_Edge works absolutely fine!!!


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

error: localhost:8080

solution: http://localhost:8080


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.


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.


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


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

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

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:

_x000D_
_x000D_
cursor:pointer;
_x000D_
_x000D_
_x000D_


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.


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/


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!


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.


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.


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.


first close all instance of chrome.

after that follow this.

I used this command on mac .

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files

For windows:

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


For Linux Python users:

import webbrowser
browser = webbrowser.get('google-chrome --allow-file-access-from-files %s')
browser.open(url)

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to three.js

ThreeJS: Remove object from scene Changing three.js background to transparent or other color How to rotate a 3D object on axis three.js? "Cross origin requests are only supported for HTTP." error when loading a local file Rotate camera in Three.js with mouse Using textures in THREE.js

Examples related to cors

Axios having CORS issue Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource How to allow CORS in react.js? Set cookies for cross origin requests XMLHttpRequest blocked by CORS Policy How to enable CORS in ASP.net Core WebAPI No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API How to overcome the CORS issue in ReactJS Trying to use fetch and pass in mode: no-cors