您可能会遇到以下错误消息:
被 cors 策略阻止:请求的资源上不存在“access-control-allow-origin”标头
此错误表示对某个地址的请求已被 cors 协议阻止,因为资源中缺少 access-control-allow-origin 标头。
跨域问题的根本原因是浏览器出于安全考虑,限制访问当前站点之外的资源。
例如,考虑托管在 http://127.0.0.1:8080/ 且具有特定页面的网站。如果您从同一站点访问资源,则没有任何限制。但如果您尝试从其他站点访问资源(例如http://127.0.0.1:8081),浏览器将阻止该请求。
注意:我们将协议、域和端口视为定义“同源”的一部分。
具有 src 属性的元素,例如 img 和 script 标签,不受此限制。
历史上,当前端和后端不分离时,页面和请求接口存在于同一个域和端口下。然后,浏览器将允许来自一个域托管的页面的请求从同一域请求资源。
例如http://127.0.0.1:8080/index.html可以自由请求http://127.0.0.1:8080/a/b/c/userlit。
现在,前端和后端分离到不同的应用程序中,这是不允许的,并且会引发 cors 问题。
来源(或源)由协议、域和端口号组成。
url 由协议、域、端口和路径组成。如果两个 url 的协议、域和端口都相同,则它们被视为“同源”。这三个元素中任何一个的差异都构成跨源请求。
考虑 https://www.baidu.com/index.html 的跨域比较:
url | cross-origin | reason |
---|---|---|
https://www.baidu.com/more/index.html | no | same protocol, domain, and port |
https://map.baidu.com/ | yes | different domain |
http://www.baidu.com/index.html | yes | different protocol |
https://www.baidu.com:81/index.html | yes | different port |
同源策略是一项基本的浏览器安全功能。如果没有它,浏览器的正常功能可能会受到威胁。 web 架构很大程度上依赖于此策略,浏览器实现它以确保安全。
同源政策包括:
在前后端分离部署的项目中,解决cors至关重要。 cookie用于存储用户登录信息,spring拦截器管理权限。当拦截器和 cors 以错误的顺序处理时,就会出现问题,导致 cors 错误。
http 请求在到达 servlet 之前首先经过过滤器,然后到达拦截器。为了确保 cors 处理发生在授权拦截之前,我们可以将 cors 配置放在过滤器中。
@configuration public class corsconfig { @bean public corsfilter corsfilter() { corsconfiguration corsconfiguration = new corsconfiguration(); corsconfiguration.addallowedorigin("*"); corsconfiguration.addallowedheader("*"); corsconfiguration.addallowedmethod("*"); corsconfiguration.setallowcredentials(true); urlbasedcorsconfigurationsource urlbasedcorsconfigurationsource = new urlbasedcorsconfigurationsource(); urlbasedcorsconfigurationsource.registercorsconfiguration("/**", corsconfiguration); return new corsfilter(urlbasedcorsconfigurationsource); } }
虽然 jsonp 可以解决前端的跨源问题,但它仅支持 get 请求,这在 restful 应用程序中受到限制。相反,您可以使用后端的跨源资源共享 (cors) 来处理跨源请求。该方案并非spring boot独有,在传统的ssm框架中也有使用。您可以通过实现 webmvcconfigurer 接口并重写 addcorsmappings 方法来配置它。
@configuration public class corsconfig implements webmvcconfigurer { @override public void addcorsmappings(corsregistry registry) { registry.addmapping("/**") .allowedorigins("*") .allowcredentials(true) .allowedmethods("get", "post", "put", "delete", "options") .maxage(3600); } }
您可以通过在@requestmapping注解中添加@crossorigin注解来为特定控制器方法启用cors。默认情况下,@crossorigin 允许@requestmapping 中指定的所有来源和http 方法。
@restcontroller @requestmapping("/account") public class accountcontroller { @crossorigin @getmapping("/{id}") public account retrieve(@pathvariable long id) { // ... } @deletemapping("/{id}") public void remove(@pathvariable long id) { // ... } }
理解@crossorigin参数:
示例:
@CrossOrigin @RestController public class PersonController { @RequestMapping(method = RequestMethod.GET) public String add() { // some code } }