跨域问题:是浏览器在执行JavaScript代码时由于浏览器的同源策略的限制,只能访问同源的资源
那我们应该如何解决跨域问题:在后端使WebMvcConfigurer接口重写addCorsMappings()方法来配置允许跨域的请求源
直接上解决方法(实测已过):
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//解决跨域问题
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedHeaders(CorsConfiguration.ALL)
.allowedMethods(CorsConfiguration.ALL)
.allowCredentials(true)
.maxAge(3600);
}
}