Threejs Model Loading: "Access to XMLHttpRequest .. from origin 'null' has been blocked by CORS policy" - How to Test Locally? Or Simple Upload?

Viewed 328

I'm playing around with three.js locally with a single HTML page, and I want to play around with loading and moving around 3D object files. From sample code I have the following copied:

var loader = new THREE.AMFLoader(); 

                loader.load( './models/rook.amf', function ( amfobject ) { //'./models/rook.amf'

                    scene.add( amfobject );
                    render();

                } );

And in Chrome I get the following error:

Access to XMLHttpRequest at 'file:///C:/Users/me/Desktop/project/models/rook.amf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

What's a simple and safe way I can get around this and get back to learning threejs? Can I add some sort of permission code somewhere? Upload my 3D model somewhere and load from an http location (and if so, where could I do this easily and free)?

2 Answers

There are two ways to solve this:

1.Change security for local files in a browser. For chrome, this can be done by searching for the path of your Chrome executable and then, on your cmd :

> "C:\PathTo\Chrome.exe" --allow-file-access-from-files

2.Run files from a local web server. This allows you to access your page as:

http://localhost/yourFile.html

You can get more information to Run a local server here

Instead of directly giving the file path, you can serve your html file with simple server: https://www.npmjs.com/package/http-server.

Open a terminal:

cd ./Users/me/Desktop/project/
npm install --global http-server
http-server -p 4200

This will serve index.html file at http://localhost:4200/ on your default browser.

Related