【发布时间】:2016-10-25 03:44:29
【问题描述】:
我正在尝试通过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)。我觉得我错过了一些简单的东西,因为注释控制器工作得很好。
【问题讨论】:
-
可能
.allowedOrigins("*").allowedHeaders("*")在全局配置中是多余的 -
你弄明白了吗?我也有这个问题。尝试了下面的答案,但对我没有用...
-
@Will 我和你在同一条船上,但设法让某些东西发挥作用。看看我在这里的回答:stackoverflow.com/a/55629589/5877810
标签: java spring-mvc http-headers cors cross-domain