Grails 3.x.x 跨域问题
Grails 官方文档:Grails CORS
跨域,简单来讲就是在浏览器的一个标签页中,使用不同域名访问资源。
例如:你在一个页面中访问 https://example1.com/file/download 的资源,同时又在此页面中访问了 https://example2.com/file/download 的资源,那么就会出现跨域问题。
Grails 官方对于跨域问题给出几种配置方法:
第一种是直接开启允许跨域,那么你项目的所有接口,都将允许跨域访问,但这存在安全上面的问题,不推荐;
第二种是指定域名的允许跨域,例如:需要相互跨域的域名只有三个 https://example1.com 、https://example2.com 和 https://example3.com,那么可以使用这种方式配置;
grails: cors: enabled: true allowedOrigins: - https://example1.com - https://example2.com - https://example3.com
第三种是不指定域名,域名可能多变,要对具体的资源接口限制跨域访问,采取以下配置;
注意这个写法有点奇怪,小引号里面跟方括号,'[/api/**]'
grails: cors: enabled: true mappings: '[/file/download]': inherit '[/file/import]': inherit '[/file/export]': inherit
第四种是既指定域名,又限制资源接口的跨域访问,使用以下配置
这种配置就是综合了 1,2,3 ,是一种完备的配置方式;
grails: cors: enabled: true allowedHeaders: - Content-Type mappings: '[/file/download]': allowedOrigins: # 限制 example1 和 example2 可以跨域访问 /file/download 资源 - https://example1.com - https://example2.com '[/file/import]': allowedOrigins: # 限制 example3 可以跨域访问 /file/import 资源,example1 和 example2 访问会提是 CORS 错误 - https://example3.com '[/file/export]': inherit # 不限制具体跨域的域名,任意具备条件的域名都可以直接访问 /file/export 资源
配置跨域访问后本地测试方式:
步骤1、首先配置一下本机 hosts 文件,给 127.0.0.1 绑定多个不同域名。hosts 文件位置:C:\Windows\System32\drivers\etc (使用管理员身份编辑)
步骤2、 然后在浏览器标签中键入你本地的接口资源
同时在控制台中使用一下代码,并用另一个域名对接口资源进行访问
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example2.com:8588/task/v1/file'); xhr.send(null); xhr.onload = function(e) { var xhr = e.target; console.log(xhr.responseText); }
控制台提示 CORS 错误,表示此接口资源不支持跨域访问
步骤3、测试一个已经开放可以支持跨域访问的接口,可以正常返回信息
以上~