问题
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 ??
回答1:
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.
回答2:
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);
});
来源:https://stackoverflow.com/questions/51674180/three-js-cross-origin-collada-file