关键F12看浏览器日志有没有Response to preflight request doesn't pass access control check,没有就说明访问路径错了
代码语言:javascript复制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;
/**
* 允许跨域
* 解决浏览器端如下报错:
* <br>Access to XMLHttpRequest at 'http://localhost:8081/Ass/login'
* <br>from origin 'http://localhost:8080' has been blocked by CORS policy:
* <br>Response to preflight request doesn't pass access control check:
* <br>No 'Access-Control-Allow-Origin' header is present on the requested resource.
* <p>CORS支持跨域配置不生效且报的比上面的少了一行是因为路径错误(例如下面的少了Ass)
* <br>Access to XMLHttpRequest at 'http://localhost:8081/list'
* <br>from origin 'http://localhost:8080' has been blocked by CORS policy:
* <br>No 'Access-Control-Allow-Origin' header is present on the requested resource.
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration configuration = new CorsConfiguration();
// 是否允许请求带有验证信息
configuration.setAllowCredentials(true);
// 允许访问的客户端域名
configuration.addAllowedOrigin("*");
// 允许服务端访问的客户端请求头
configuration.addAllowedHeader("*");
// 允许访问的方法名,GET POST等
configuration.addAllowedMethod("*");
source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
}
代码语言:javascript复制 // 携带 cookie 以便 session 生效
axios.defaults.withCredentials=true;