我尝试按照Spring网站的建议实现GLOBAL CORS,以便将我的spring boot应用程序部署到Pivotal Cloud Foundry。
https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/cors.html
但是,当我向服务端点发送OPTIONS消息时,响应不会返回任何CORS头。因此,应用程序无法在预检后进行POST调用。这是我的实施。
@Configuration
@EnableWebMvc
public class CORSConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("*/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "OPTIONS")
.allowedHeaders("Content-Type", "Authorization")
.allowCredentials(false).maxAge(3600);
}
}
我错过了什么吗?
答案 0 :(得分:2)
确定。我找到了问题所在。单独的HTTP OPTIONS请求不构成飞行前请求。为了将OPTIONS视为飞行前请求,它需要另外2个请求标头。一个是Origin,我在请求中添加了。但是,我错过了Access-Control-Request-Method。浏览器生成的转发前请求将包含所有3个http请求标头。一旦我添加了所有3个请求标头,我就会在响应中看到我的CORS标头。
以下是示例代码和响应。
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;
@Configuration
@EnableWebMvc
public class CORSConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST")
.allowedHeaders("Content-Type", "Authorization")
.allowCredentials(false)
.maxAge(32400); // 9 hours max age
}
}
以下是请求:
OPTIONS /my-end-point HTTP/1.1
Host: my-app.my-domain.com
Origin: http://localhost:8090
Access-Control-Request-Method: POST
Cache-Control: no-cache
Postman-Token: bc7171bc-7f84-3b44-a304-818627411a72
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
以下是回复。
access-control-allow-methods →POST
access-control-allow-origin →*
access-control-max-age →32400