【Three.js】Refused to connect to xxx because it violates the document‘s Content Security Policy.-CSDN博客

504 阅读1分钟

问题描述

当使用 Three.js 的 OBJLoader 和 MTLLoader 导入模型及其贴图时,控制台报错,错误信息如下。

App.vue:38 Refused to connect to 'file:///xxx.obj' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

App.vue:38 Refused to connect to 'file:///xxx.obj' because it violates the document's Content Security Policy.

在这里插入图片描述


原因分析

这个错误是由于浏览器的 Content Security Policy (CSP) 限制导致的。默认情况下,浏览器只允许从同源地址加载资源,而不允许从文件系统加载资源。


解决方案

在 index.html 的 header 标签中将原有的 Content-Security-Policy

    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
    />

改为

    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'self' file: data:; script-src 'self'; style-src 'self' 'unsafe-inline'; "
    />

这样做的目的是允许加载来自文件系统的资源,但是请注意,这可能会增加一些安全风险,因为它打破了同源策略。因此,在生产环境中,应该谨慎使用此方法,并考虑其他安全的解决方案。