意图:使用基于SpringMVC的Web应用程序公开的Angular中的REST API。两者都在不同的主机中运行
问题:
尽管我要请求的API是GET
请求,但Angular幕后首先向REST API SpringMVC服务器发出了OPTIONS
请求。这将抛出500
服务器错误。服务器控制器资源方法具有必要的批注以启用CORS支持。
[使用邮递员工具尝试使用相同的API,并且提供了期望的输出而没有任何错误。
我正在使用的技术堆栈:
Angular 6,Spring MVC(显式配置了[[no Spring安全性] [基于Java config的配置]。
Angular捕获的错误消息:
Access to XMLHttpRequest at 'http://localhost:8080/v1/create' from origin
'http://localhost:4200' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested resource.
代码段:
角码:
public createDomainObj() {
return this.http.post('http://localhost:8080/v1/create', request body parameter)
}
SpringMVC代码:
@ResponseBody
@RequestMapping(value = "/v1/create", method = RequestMethod.POST)
@AccessController(accessLevel = "Anonymous")
public <APIResponseModelClass> anAPIMethod(@RequestBody param1, param2) {
//code logic
return <obj>;
}
已经尝试过的内容:
SpringMVC中的CORS过滤器,注释的所有组合,但没有运气。还尝试了以下链接中提到的建议,但均未成功:
https://www.baeldung.com/spring-security-cors-preflight
How to add Access-Control-Allow-Origin to jetty server
如何使Angular从具有OPTIONS预检方面的SpringMVC中使用REST API?
CORS:Response to preflight request doesn't pass access control
,有两种类型的请求,1)简单有一些条件,可轻松交换cors标头,允许的方法,标头,内容类型2)飞行前例如,那些与简单请求条件不符的事是飞行前检查,我们向服务器发送DELETE请求。浏览器发送带有标头的OPTIONS请求,该标头包含有关我们发出的DELETE请求的信息。 OPTIONS /users/:id
Access-Control-Request-Method: DELETE
简单的方法是,您可以删除或更改不需要的任何复杂标头。
Header set Access-Control-Allow-Origin "*"
设置将对简单的CORS请求起作用,因此对于具有自定义标头值的更复杂的请求将不起作用,这就是浏览器的预检机制,它检查服务是否接受请求,它包括的记住,
Access-Control-Request-Headers Access-Control-Request-Method Access-Control-Allow-Origin
似乎您需要在http configure thats cors过滤器中添加cors,启用cors的不同方法,1)控制器方法CORS配置
@CrossOrigin(origins = "http://localhost:9000") @GetMapping("/greeting") public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) { System.out.println("==== in greeting ===="); return new Greeting(counter.incrementAndGet(), String.format(template, name)); }
2)全局CORS配置
public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000"); } }; }
3)启用网络安全,尝试添加http.cors()
@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // ... http.cors(); } }