[英]CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API & VUE
I have been getting the following errors when making requests from the frontend(built with vue) to the backend(built with spring boot)从前端(使用 vue 构建)向后端(使用 spring 引导构建)发出请求时出现以下错误
Access to XMLHttpRequest at 'http://api.app.com/productorder/all' from origin 'http://my.app.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is my WebSecurity Class:这是我的 WebSecurity Class:
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
private UserDetailsServiceImpl userDetailsService;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Value("${cors.allowed-origins}")
private String allowedOrigins;
public WebSecurity(UserDetailsServiceImpl userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.antMatchers("/v2/**", "/configuration/**", "/swagger*/**", "/webjars/**")
.permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
// this disables session creation on Spring Security
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();
config.setExposedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
"Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"));
// Move this into properties files
// make sure to split the array before adding below
config.setAllowedOrigins(Arrays.asList("http://localhost:3000","http://localhost:8080","http://my.app.com", "http://api.app.com"));
config.setAllowedMethods(Arrays.asList("GET","POST", "UPDATE", "DELETE", "OPTIONS", "PUT"));
source.registerCorsConfiguration("/**", config);
return source;
}
}
Create a Once per request filter add this response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH"); response.setHeader("Access-Control-Allow-Headers", "Date, Content-Type, Accept, X-Requested-With, Authorization, From, X-Auth-Token, Request-Id"); response.setHeader("Access-Control-Expose-Headers", "Set-Cookie"); response.setHeader("Access-Control-Allow-Credentials", "true");
创建一个每个请求过滤器一次添加此
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH"); response.setHeader("Access-Control-Allow-Headers", "Date, Content-Type, Accept, X-Requested-With, Authorization, From, X-Auth-Token, Request-Id"); response.setHeader("Access-Control-Expose-Headers", "Set-Cookie"); response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH"); response.setHeader("Access-Control-Allow-Headers", "Date, Content-Type, Accept, X-Requested-With, Authorization, From, X-Auth-Token, Request-Id"); response.setHeader("Access-Control-Expose-Headers", "Set-Cookie"); response.setHeader("Access-Control-Allow-Credentials", "true");
Use CorsConfiguration#setAllowedHeaders(List<String> allowedHeaders)
( quote ):使用
CorsConfiguration#setAllowedHeaders(List<String> allowedHeaders)
( 引用):
Set the list of headers that a pre-flight request can list as allowed for use during an actual request.
将飞行前请求可以列出的标头列表设置为允许在实际请求期间使用。 The special value "*" allows actual requests to send any header.
特殊值“*”允许实际请求发送任何 header。
A header name is not required to be listed if it is one of: Cache-Control, Content-Language, Expires, Last-Modified, or Pragma.
如果 header 名称是以下之一,则无需列出:Cache-Control、Content-Language、Expires、Last-Modified 或 Pragma。
By default this is not set.
默认情况下未设置。
For example, add in the corsConfigurationSource()
method:例如,在
corsConfigurationSource()
方法中添加:
config.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Origin", "Authorization", "Accept", "Content-Type"));
Notice that you may not need Authorization
if it isn't used and may need to add other headers as well.请注意,如果不使用授权,您可能不需要
Authorization
,并且可能还需要添加其他标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.