java - Angular 6 - Spring MVC::Options 预检请求抛出 500 内部服务器错误

标签 java spring-mvc cors angular6 preflight

意图:
在 Angular 中使用通过基于 SpringMVC 的 Web 应用程序公开的 REST API。两者都在不同的主机上运行

问题:

虽然我请求的 API 是一个GET 请求,但 Angular 幕后 首先向 REST API 发出一个 OPTIONS 请求SpringMVC 服务器。这会返回一个 500 服务器错误(请参阅下面的 CURL 输出)。

尝试使用 Postman 工具(GET 请求)访问相同的 API,令人惊讶的是它给出了所需的输出(即也给出了 Access-Control-Allow-Origin header )而没有任何错误,但是 OPTIONS 请求抛出 500 服务器错误。

我正在使用的技术栈:

  • Angular 6(在 NodeJS 上运行)
  • Spring MVC 4.3.6.RELEASE(没有 Spring 安全显式配置)[ Java配置基于Spring配置]
  • Jetty-Runner 9.4.1(运行 Spring MVC webapp 的 WAR 文件)。

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

CURL 能够重现问题:

请求:

curl -H "Origin:*" -H "Access-Control-Request-Method: GET, POST, PUT, DELETE" 
-H "Access-Control-Request-Headers: X-Requested-With" 
-X OPTIONS --verbose  http://localhost:8080/v1/create

响应:

Trying 127.0.0.1...
 Connected to localhost (127.0.0.1) port 8080 (#0)
 OPTIONS /v1/create HTTP/1.1
 Host: localhost:8080
 User-Agent: curl/7.47.0
 Accept: */*
 Origin:*
 Access-Control-Request-Method: GET, POST, PUT, DELETE
 Access-Control-Request-Headers: X-Requested-With
 Content-Length: 392
 Content-Type: application/x-www-form-urlencoded

 upload completely sent off: 392 out of 392 bytes
 HTTP/1.1 500 Server Error
 Connection: close
Server: Jetty(9.4.2.v20170220)
Closing connection 0


那么,如何让 Angular 从具有 OPTIONS 预检方面的 SpringMVC 使用 REST API?

最佳答案

关于问题,我可以说, CORS:对预检请求的响应未通过访问控制
有两种类型的请求,
1) 简单
有一些标准,cors header 的简单交换,允许的方法, header ,内容类型
2) 预检
那些不符合简单请求标准的是预检,例如,
我们向服务器发送一个 DELETE 请求。浏览器发送 OPTIONS 请求,其 header 包含有关我们发出的 DELETE 请求的信息。

OPTIONS /users/:id 
Access-Control-Request-Method: DELETE 

简单的修复方法是您可以删除或更改任何不需要的复杂 header 。

Header set Access-Control-Allow-Origin "*" 设置这将适用于简单的 CORS 请求,因此对于具有自定义 header 值的更复杂的请求将不起作用,这就是浏览器的预检机制它检查服务是否接受请求,
请记住,它包括,

Access-Control-Request-Headers
Access-Control-Request-Method
Access-Control-Allow-Origin

看来您需要在 http 配置中添加 cors,这就是 cors 过滤器, 启用 cors 的不同方式,
1) Controller 方式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();
    }
}

关于java - Angular 6 - Spring MVC::Options 预检请求抛出 500 内部服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59169820/

相关文章:

java - 使用泛型创建参数类

java - Google Maps API 上的 ZoomControls - 如何将它移动到 ButtonBar 上方?

java - 如何让log4j记录到文件并打印到控制台

java - 如何在 Spring MVC 的 JavaBean 中将下划线样式查询字符串转换为 Camel 样式属性?

javascript - 为什么我的 API 中未启用 CORS?

c# - 如何在 ASP.NET MVC 中启用跨源请求

java - 在构造函数中使用 "this instanceof …"或 "getClass()"是否安全?

java - @Scheduled 从 Controller

ajax - Web 套接字会让 ajax/CORS 过时吗?

angularjs - 请求的资源上不存在 'Access-Control-Allow-Origin' header 。 Ionic、AngularJS、Spring Boot 1.3