在我做微信支付项目中的问题:跨域访问,最开始用视频上的注解@CrossOrigin ,后端的资无法访问源,我自己在网上找了找,就是添加一个过滤器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfigFilter {
@Bean
public CorsFilter corsfilter(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource =
new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
结果后端节能访问了
2.还有第二种方法,这种方法我没有试成功,劳驾各位大哥大写指点一下
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") //映射
.allowedHeaders("*") //请求头
.allowedOriginPatterns("/**") //允许哪些域访问
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
.allowCredentials(true)//是否允许携带cookie
.maxAge(3600); //设置时间
}
}
最终结果
解决跨域视频(非本人视频):什么是跨域以及如何解决?通俗易懂带你彻底搞定_哔哩哔哩_bilibili