我正在尝试通过 WebMvcConfigurerAdapter
全局配置 CORS,如下所示。为了进行测试,我通过我创建的用于模拟外部服务的小型节点应用程序访问了我的 API 端点。当我尝试这种方法时,响应不包含正确的标头并且失败了
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
注释时,它可以很好地响应正确的标头。
@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 )。我觉得我错过了一些简单的东西,因为注释控制器工作得很好。
原文由 Adam James 发布,翻译遵循 CC BY-SA 4.0 许可协议
为了使全局 CORS 配置起作用,客户端必须在 OPTIONS 请求中添加这两个标头。
然而,@CrossOrigin 注释只需要“Origin”标头。
您的客户端可能添加了“Origin”标头,但缺少“Access-Control-Request-Method”……这就是为什么它适用于@CrossOrigin,但不适用于全局配置。