我尝试按照这个spring站点为我的spring boot应用程序实现全局CORS,该应用程序被部署到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);
}
}
我错过了什么吗?
发布于 2018-02-13 19:17:33
好的。我找到了问题所在。HTTP OPTIONS请求本身并不构成飞行前请求。为了将OPTIONS考虑为飞行前请求,它还需要两个请求头。一个是Origin,它是我添加到请求中的。然而,我遗漏了Access-Control-Request方法。由浏览器生成的飞行前请求将包含所有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
https://stackoverflow.com/questions/48712638
复制相似问题