Spring Global CORS配置无效,但控制器级配置有效

Ada*_*mes 30 java spring-mvc cross-domain http-headers cors

我试图通过WebMvcConfigurerAdapter如下所示全局配置CORS .测试我通过我创建的小节点应用程序来模拟外部服务.当我尝试这种方法时,响应不包含正确的标题,并失败

XMLHttpRequest cannot load http://localhost:8080/api/query/1121. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:333' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)

全球配置

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/query/**")
                    .allowedOrigins("*")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我使用这样的@CrossOrigin注释时,它可以很好地响应正确的标题.

@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
@RestController
@RequestMapping(value = "/api/query", produces = MediaType.APPLICATION_JSON_VALUE)
public class QueryController {
   ......
}
Run Code Online (Sandbox Code Playgroud)

产生

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:333
Run Code Online (Sandbox Code Playgroud)

我缺少使全局配置工作的原因(按照https://spring.io/blog/2015/06/08/cors-support-in-spring-framework中的说明进行操作).我觉得我错过了一些简单的东西,因为注释控制器工作得很好.

out*_*dev 17

为了使全局CORS配置起作用,客户端必须在OPTIONS请求中添加这两个头.

Origin: http://host.com
Access-Control-Request-Method: POST
Run Code Online (Sandbox Code Playgroud)

但是@CrossOrigin注释只需要"Origin"标题.
您的客户端可能会添加"Origin"标头,但缺少"Access-Control-Request-Method".....这就是为什么它适用于@CrossOrigin,但不适用于全局配置.

  • 如果代码在 Web 浏览器中运行,则客户端无法执行此操作。 (4认同)
  • 我收到“拒绝设置不安全标头“Access-Control-Request-Method””,chrome“83.0.4103.61(官方版本)(64 位)” (2认同)

dhy*_*ngh 7

您没有在其中声明方法,默认情况下仅接受 get 方法。尝试registry.allowedMethods("*");


Bri*_*zel 0

我认为您的映射定义缺少*:

registry.addMapping("/api/query/**")
Run Code Online (Sandbox Code Playgroud)

如果没有这个额外的*,此配置不会映射到/api/query/1121请求路径(但它可以在/api/query/5)上工作。

  • 感谢您的回复,我也尝试了`"/api/query/**"`,但没有成功。最初我什至用 `registry.addMapping("/**")` 实现了一个 'hello world' 类型的实现,但这并没有什么区别..我是否必须以某种方式指定它位于端口 8080 上?我什至不知道...看起来应该可以正常工作 (2认同)