Access to XMLHttpRequest at 'http://localhost:8080/test/test1?page=1&limit=10' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
前后端分离跨域问题
springboot后台添加配置类
这里需要注意的是 registry.allowedOrigins("*"),这个方法适用于SpringBoot版本2.3.x及以下版本,
如果你的SpringBoot版本是2.4.x及以上则需要调用registry.allowedOriginPatterns("*")方法,
如果是2.4.x及以上版本调用 registry.allowedOrigins("*")方法配置不会生效;
package com.dgr.manage.config.web;
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 WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//springboot 2.3.x及以下 使用
//.allowedOrigins("*")
//springboot 2.4.x及以上 使用
.allowedOriginPatterns("*")
.allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Access-Control-Allow-Headers",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Origin",
"Access-Control-Max-Age",
"X-Frame-Options")
.allowCredentials(true).maxAge(3600);
}
}