Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,

时间:2024-03-16 12:41:07

问题:Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,

分析:由错误信息可知是因为浏览器不支持跨域导致的,但由图能看出我是在本地直接打开页面,没有相应的后台服务器;由地址栏能看出这是采用的file协议,而我的JS代码中需要访问某个地址,而浏览器不支持file协议访问应用。所以解决这个问题有两个方法,一是提供后台服务器,二是使浏览器支持file协议访问。

方案一:提供静态服务器

其实我们在本地开发一个简单的web项目,不一定需要自己搭建服务器,仅需要提供一个静态服务器即可。
因为本人用Sublime Text作为你的编辑器,所以需要找一个插件来完成前端的联调测试,那就是Sublime Text的服务器插件:SublimeServer。使用了该插件后,你不在需要单独的启动Tomcat或者Apache这样的重型服务器,就可以完成HTML和Javascript在服务器的联调。

  • 打开Package Control
    Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,

  • 输入Install Package打开插件安装命令
    Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,

  • 输入Sublime Server,回车直接安装即可
    Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,
    出现如图所示内容,说明安装成功。但是不要急于启动,先继续操作下一步。

  • 在启动之前,需要将运行的文件夹加入Sublime Project
    Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,
    选择文件夹加入Sublime Project后,就可以启动Sublime Server。

  • 启动效果,地址栏输入:localhost:8080
    Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,

  • 打开相应的页面
    Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,
    细心观察可以发现,地址栏的地址和之前报错的地址已经不一样了。

  • 修改端口
    打开配置文件
    Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension,
    修改port字段即可:

{
	"attempts": 5,
	"autorun": false,
	"defaultExtension": ".html",
	"interval": 500,
	"mimetypes":
	{
		"": "application/octet-stream",
		".c": "text/plain",
		".h": "text/plain",
		".py": "text/plain"
	},
	"port": 8080
}

参考链接:http://www.daxiblog.com/2016/09/17/让sublime-text成为静态web服务器:sublimeserver/

方案二:使浏览器支持file协议
由于该方案本人未操作过,因此只附上参考链接(仅供参考):
https://blog.csdn.net/superit401/article/details/72772658