前段时间做一个vue打包成安卓和IOS的App,遇到了跨域问题,直接拿了之前项目的配置,却不起作用。
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 CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}
但是还是不行,后面查明是因为之前项目nginx和项目在一个服务器,而APP的前端是在移动端的。解决方法有所不同,如下
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class LakeAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedHeaders("*")
.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
.exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L)
.maxAge(3600);
}
}
完美解决。