| | |
| | | import org.springframework.web.cors.CorsConfiguration; |
| | | import org.springframework.web.cors.CorsConfigurationSource; |
| | | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; |
| | | import org.springframework.web.servlet.config.annotation.CorsRegistry; |
| | | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; |
| | | |
| | | /** |
| | | * @author yami |
| | | */ |
| | | @Configuration |
| | | public class CorsConfig { |
| | | public class CorsConfig implements WebMvcConfigurer { |
| | | |
| | | /** |
| | | * 修改为添加而不是设置,* 最好生产环境改为实际的需要, 这里可以用多个add配置多个域名 |
| | | * configuration.addAllowedOrigin("http://localhost:8080"); |
| | | * configuration.addAllowedOrigin("http://192.168.1.6:8080"); |
| | | * @return CorsConfigurationSource |
| | | */ |
| | | @Override |
| | | public void addCorsMappings(CorsRegistry registry) { |
| | | registry.addMapping("/**") |
| | | .allowedOriginPatterns("*") // 使用 * 允许所有来源 |
| | | .allowCredentials(true) // 允许凭证 |
| | | .allowedMethods("GET", "POST", "PUT", "DELETE") // 指定允许的 HTTP 方法 |
| | | .allowedHeaders("Content-Type", "Authorization") // 指定允许的头部 |
| | | .maxAge(3600); // 可选,指定预检请求缓存时间 |
| | | } |
| | | |
| | | @Bean |
| | | public CorsConfigurationSource corsConfigurationSource() { |
| | | CorsConfiguration configuration = new CorsConfiguration(); |