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,但不适用于全局配置.
我认为您的映射定义缺少*:
registry.addMapping("/api/query/**")
Run Code Online (Sandbox Code Playgroud)
如果没有这个额外的*,此配置不会映射到/api/query/1121请求路径(但它可以在/api/query/5)上工作。
| 归档时间: |
|
| 查看次数: |
22015 次 |
| 最近记录: |