Spring Global CORS配置不起作用,但控制器级配置不起作用 [英] Spring Global CORS configuration not working but Controller level config does

查看:2558
本文介绍了Spring Global CORS配置不起作用,但控制器级配置不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to configure CORS globally via WebMvcConfigurerAdapter shown below. To test I am hitting my API endpoint via a small node app I created to emulate an external service. When I try this approach the response does not contain the correct headers and fails with

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.

全球配置

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);
        }
}

但是当我使用时@CrossOrigin 注释就像这样它可以正常响应正确的标题。

However when I utilize the @CrossOrigin annotation like so it works just fine responding with the proper headers.

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

产生

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:333

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

What am I missing to make the global config work (followed instructions here https://spring.io/blog/2015/06/08/cors-support-in-spring-framework). I feel like I'm missing something simple since annotating the controller works just fine.

推荐答案

为了使全局CORS配置为工作,客户必须在OPTIONS请求中添加这两个标题。

In order for the global CORS config to work, the client must add these two headers in the OPTIONS request.

Origin: http://host.com
Access-Control-Request-Method: POST

但@CrossOrigin注释仅需要Origin标题。

您的客户端可能添加了Origin标题,但缺少Access-Control-Request-Method.....这就是为什么它适用于你@CrossOrigin,但不是' t与全局配置。

However the @CrossOrigin annotation requires just the "Origin" header.
Your client probably adds the "Origin" header but is missing the "Access-Control-Request-Method".....thats why it works for you with the @CrossOrigin, but doesn't with the global config.

这篇关于Spring Global CORS配置不起作用,但控制器级配置不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆