我正在尝试通过如下所示的WebMvcConfigurerAdapter全局配置CORS。为了进行测试,我通过一个模拟外部服务而创建的小节点应用程序访问了API端点。当我尝试这种方法时,响应不包含正确的 header ,并且失败

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批注时,它可以很好地响应适当的 header 。
@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的说明进行操作)。我觉得我缺少一些简单的东西,因为对 Controller 进行注释就可以了。

最佳答案

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

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

但是@CrossOrigin批注仅需要“Origin” header 。
您的客户端可能会添加“Origin” header ,但缺少“Access-Control-Request-Method” .....这就是为什么它与@CrossOrigin一起使用但对全局配置不起作用的原因。

10-07 19:07
查看更多