跨域问题解决Access to image at 'file:///png' from origin 'null' has been blocked by CORS policy

在谷歌浏览器中出现

Access to image at 'file:///C:/Users/DK/Desktop/threejs%E5%AD%A6%E5%A0%82/material/g8.png' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

这是浏览器安全不允许跨域访问,即使是访问本地文件也不行,必须是以http,https网络请求方式访问。

网上解决办法是:crossorigin="anonymous"

以及浏览器快捷方式加参数:chrome.exe --disable-web-security   (后患无穷)

 

正确的解决办法是:建立本地服务器,现在介绍一分钟建立本地服务器的办法

方法一:Servez

简介:https://greggman.github.io/servez/

 

该服务器支持mac,linux,windows。

window版直接下载exe文件即可,有界面,选择要建站的文件夹,点Start 就可以了。相当简单。

 

方法二:Node.js http-server

下载安装http-server

 npm install --global http-server
C:\Users\mybj\AppData\Roaming\npm\hs -> C:\Users\mybj\AppData\Roaming\npm\node_modules\http-server\bin\http-server
C:\Users\mybj\AppData\Roaming\npm\http-server -> C:\Users\mybj\AppData\Roaming\npm\node_modules\http-server\bin\http-server
+ http-server@0.12.3
added 30 packages from 40 contributors in 6.6s

启动http-server

命令

http-server [path] [options]

[path]的默认值:先找 ./public ,否则使用 ./ 。

例如:

复制$ http-server
Starting up http-server, serving ./
Available on:
  http://192.168.17.140:8081
  http://192.168.44.1:8081
  http://192.168.208.1:8081
  http://192.168.137.1:8081
  http://127.0.0.1:8081
Hit CTRL-C to stop the server

效果如下:
http-server

 

posted @ 2021-11-29 15:37  小y  阅读(14348)  评论(0编辑  收藏  举报