创建配置类,并确保该类位于 Spring 的扫描路径下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Configuration public class CorsConfig {
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .allowedOrigins("*"); } }; } }
|
验证跨域请求
在不同域名的页面中打开浏览器控制台,执行:
1 2 3 4 5 6 7
| var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://请求url'); xhr.send(null); xhr.onload = function(e) { var xhr = e.target; console.log(xhr.responseText); };
|