setWithCredentials()方法是three.js中Loader对象的一个方法之一。这个方法的作用是设置在使用XHRLoader时是否允许跨域访问。
在JavaScript中,当一个请求跨越不同的域名、协议或端口时,就会被称为跨域请求。在默认情况下,跨域请求是不允许的,因为这可能导致安全问题。而setWithCredentials()方法允许XHRLoader发起跨域请求时携带Cookie以及HTTP认证信息等敏感信息。
loader.setWithCredentials( value )
value:boolean类型,表示是否允许跨域请求。在使用XHRLoader加载跨域资源时,可以先调用setWithCredentials(true)开启允许跨域请求。示例代码:
var loader = new THREE.XHRLoader();
loader.setWithCredentials( true );
loader.load(
'http://example.com/sample_vrml.wrl',
function ( response ) {
console.log( '成功加载 VRML 文件' );
},
function ( xhr ) {
console.log( (xhr.loaded / xhr.total * 100) + '% 已加载' );
},
function ( xhr ) {
console.log( '加载 VRML 文件失败' );
}
);
XHRLoader时可以调用setWithCredentials()方法。其他Loader类不支持此方法。