"No 'Access-Control-Allow-Origin' header is present on the requested resource" 从本地服务器加载图像时?

"No 'Access-Control-Allow-Origin' header is present on the requested resource" when loading image off local server?

我正在尝试使用 pixi.js 库从我的本地主机服务器加载一个简单的测试图像,但是加载图像会导致此错误:

Access to Image at
'http://localhost:8080/local_files/assests/images/test_image.jpg' from origin 'null'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present 
on the requested resource. Origin 'null' is therefore not allowed access.

我的代码加载图像:

//load test image 
var texture = PIXI.Texture.fromImage("http://localhost:8080/local_files/assests/images/test_image.jpg");

Allow-origin - 通常意味着您只能加载您所在的同一域中的资源。因此,如果你想加载 "localhost" 资源,你需要在本地主机上。 然而,在这种情况下,问题可能只是您试图从无法访问该本地资源的远程服务器加载本地主机资源。

您需要记住在远程服务器中使用图像。如果可能,为每个资源(图像、js 文件等)使用相同的域。对于静态资源,最简单的做法是使用关系路径而不是绝对路径(“./images/image.png”而不是“http://localhost/images/image.png”)。

希望对您有所帮助

如果图像是从不同的域加载的,当图像资源被JavaScript(编辑等)操作时,应用Same Origin Policy

在这个问题的情况下,HTML 是从本地文件系统加载的(来源是 null),但图像是从 http://localhost:8080 加载的。因此,当使用pixi.js操作图像(读取图像数据并将其存储为纹理)时,浏览器会报错,因为http://localhost:8080不支持CORS

要解决这个问题,有两种方法:

  1. http://localhost:8080 上部署 HTML 文件并从那里加载它。
  2. http://localhost:8080 中启用 CORS