THREE JS Cross origin Collada file

2019-09-20 18:37发布

When trying to load Collada file from my server I get the Cross Origin error so my file is inaccessible

Link: https://codepen.io/RedKizaru/pen/MBXYbV

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://hydle.000webhostapp.com/host/obj/stand.dae";
script.integrity = "sha384-tSi+YsgNwyohDGfW/VhY51IK3RKAPYDcj1sNXJ16oRAyDP++K0NCzSCUW78EMFmf";
script.crossOrigin = "anonymous";
document.getElementsByTagName("head")[0].appendChild(script);

How can I get rid of the cross origin block ??

2条回答
在下西门庆
2楼-- · 2019-09-20 18:55

Problem:

Many Apache servers (like yours) have disabled resource-sharing with other servers by default. In your case, https://hydle.000webhostapp.com is not allowed to share the .dae file with https://codepen.io, which is why you're getting this error.


Solution 1:

If you host your code and your .dae file on the same server, you won't run into any CORS issues, since they both have the same origin.


Solution 2:

You'll need to upload a PHP script to your server that allows resource-sharing to specific domains. I won't write the whole code for you, but it goes something like this:

script.php:

<?php
    header("Access-Control-Allow-Origin: https://codepen.io");
    echo readfile("/path/to/file.dae");
?>

then you upload script.php to your server, and you'll be able to load that resource from codepen.io via JavaScript:

script.src = "https://hydle.000webhostapp.com/host/obj/script.php";

Accessing script.php this way will return the contents of file.dae. I don't recommend solution 2 because of security issues, but it's what you asked for. For more info on PHP's readfile, you can read its documentation.

查看更多
我想做一个坏孩纸
3楼-- · 2019-09-20 19:00

Instead of trying to append your collada file as a script, try this:

var url = "https://hydle.000webhostapp.com/host/obj/stand.dae";
var loader = new THREE.ColladaLoader();
loader.setCrossOrigin("anonymous");
loader.load(url, function (collada) {
    scene.add(collada.scene);
});
查看更多
登录 后发表回答