Spring CORS 不存在“Access

编程入门 行业动态 更新时间:2024-10-27 22:23:13
本文介绍了Spring CORS 不存在“Access-Control-Allow-Origin"标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

将 web.xml 移植到 java config 后出现以下问题

请求的资源上不存在Access-Control-Allow-Origin"标头.因此,不允许访问 Origin 'localhost:63342'.

基于一些Spring的参考资料,尝试了以下尝试:

@Configuration@ComponentScan(basePackageClasses = AppConfig.class, useDefaultFilters = false, includeFilters = {@Filter(org.springframework.stereotype.Controller.class) })@EnableWebMvc公共类 WebConfig 扩展了 WebMvcConfigurerAdapter {@覆盖公共无效 addCorsMappings(CorsRegistry 注册表){registry.addMapping("/*").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT").allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",访问控制请求标头").exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials").allowCredentials(true).maxAge(3600);}}

所选择的值取自有效的 web.xml 过滤器:

<filter-name>Cors​​Filter</filter-name><filter-class>org.apache.catalina.filters.CorsFilter</filter-class><初始化参数><param-name>cors.allowed.origins</param-name><参数值>*</参数值></init-param><初始化参数><param-name>cors.allowed.methods</param-name><param-value>GET,POST,HEAD,OPTIONS,PUT</param-value></init-param><初始化参数><param-name>cors.allowed.headers</param-name><param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value></init-param><初始化参数><param-name>cors.exposed.headers</param-name><param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value></init-param><初始化参数><param-name>cors.support.credentials</param-name><param-value>true</param-value></init-param><初始化参数><param-name>cors.preflight.maxage</param-name><参数值>10</参数值></init-param></过滤器><过滤器映射><filter-name>Cors​​Filter</filter-name><url-pattern>/*</url-pattern></过滤器映射>

为什么 Spring java 配置方法不像 web.xml 文件那样工作的任何想法?

解决方案

将 CorsMapping 从 registry.addMapping("/*") 更改为 registry.addMapping("/**") 在 addCorsMappings 方法中.

查看此 Spring CORS 文档.>

来自文档 -

为整个应用程序启用 CORS 非常简单:

@Configuration@EnableWebMvc公共类 WebConfig 扩展了 WebMvcConfigurerAdapter {@覆盖公共无效 addCorsMappings(CorsRegistry 注册表){registry.addMapping("/**");}}

您可以轻松更改任何属性,并且仅将此 CORS 配置应用于特定路径模式:

@Configuration@EnableWebMvc公共类 WebConfig 扩展了 WebMvcConfigurerAdapter {@覆盖公共无效 addCorsMappings(CorsRegistry 注册表){registry.addMapping("/api/**").allowedOrigins("domain2").allowedMethods("PUT", "DELETE").allowedHeaders("header1", "header2", "header3").exposedHeaders("header1", "header2").allowCredentials(false).maxAge(3600);}}

控制器方法 CORS 配置

@RestController@RequestMapping("/账户")公共类 AccountController {@CrossOrigin@RequestMapping("/{id}")公共帐户检索(@PathVariable Long id){//...}}

为整个控制器启用 CORS -

@CrossOrigin(origins = "domain2", maxAge = 3600)@RestController@RequestMapping("/账户")公共类 AccountController {@RequestMapping("/{id}")公共帐户检索(@PathVariable Long id){//...}@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")public void remove(@PathVariable Long id) {//...}}

您甚至可以同时使用控制器级别和方法级别的 CORS 配置;然后 Spring 将结合来自两个注解的属性来创建合并的 CORS 配置.

@CrossOrigin(maxAge = 3600)@RestController@RequestMapping("/账户")公共类 AccountController {@CrossOrigin("domain2")@RequestMapping("/{id}")公共帐户检索(@PathVariable Long id){//...}@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")public void remove(@PathVariable Long id) {//...}}

I am getting the following problem after porting web.xml to java config

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:63342' is therefore not allowed access.

Based on a few Spring references, the following attempt has been tried:

@Configuration @ComponentScan(basePackageClasses = AppConfig.class, useDefaultFilters = false, includeFilters = { @Filter(org.springframework.stereotype.Controller.class) }) @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/*").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT") .allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers") .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials") .allowCredentials(true).maxAge(3600); } }

The values chosen were taken from a working web.xml filter:

<filter> <filter-name>CorsFilter</filter-name> <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> <init-param> <param-name>cors.allowed.origins</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.allowed.methods</param-name> <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value> </init-param> <init-param> <param-name>cors.allowed.headers</param-name> <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value> </init-param> <init-param> <param-name>cors.exposed.headers</param-name> <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value> </init-param> <init-param> <param-name>cors.support.credentials</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>cors.preflight.maxage</param-name> <param-value>10</param-value> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

Any ideas why the Spring java config approach is not working like the web.xml file did?

解决方案

Change the CorsMapping from registry.addMapping("/*") to registry.addMapping("/**") in addCorsMappings method.

Check out this Spring CORS Documentation .

From the documentation -

Enabling CORS for the whole application is as simple as:

@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } }

You can easily change any properties, as well as only apply this CORS configuration to a specific path pattern:

@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("domain2") .allowedMethods("PUT", "DELETE") .allowedHeaders("header1", "header2", "header3") .exposedHeaders("header1", "header2") .allowCredentials(false).maxAge(3600); } }

Controller method CORS configuration

@RestController @RequestMapping("/account") public class AccountController { @CrossOrigin @RequestMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ... } }

To enable CORS for the whole controller -

@CrossOrigin(origins = "domain2", maxAge = 3600) @RestController @RequestMapping("/account") public class AccountController { @RequestMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ... } @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") public void remove(@PathVariable Long id) { // ... } }

You can even use both controller-level and method-level CORS configurations; Spring will then combine attributes from both annotations to create merged CORS configuration.

@CrossOrigin(maxAge = 3600) @RestController @RequestMapping("/account") public class AccountController { @CrossOrigin("domain2") @RequestMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ... } @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") public void remove(@PathVariable Long id) { // ... } }

更多推荐

Spring CORS 不存在“Access

本文发布于:2023-10-12 01:04:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   Spring   CORS   Access

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!