在前端发起请求,获取 subject 服务相关数据时,出现了 CORS
问题,刚开始我 在 SpringCloud Gateway
中配置了跨域,但是并没有起作用,我又在相关的微服务中,通过 WebConfig implements WebMvcConfigurer
再次配置了跨域
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import org.springframework.context.annotation.Bean; 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 WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:5173") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }
|
但仍 未通过,然后想到了 我使用了 satoken
,觉得会先一步将请求给打回去,就在 satoken
中配置了 跨域
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
@Configuration public class SaTokenConfigure implements WebMvcConfigurer {
@Bean public SaServletFilter getSaServletFilter() { return new SaServletFilter() .addInclude("/**").addExclude("/favicon.ico") .setAuth(obj -> { SaManager.getLog().debug("----- 请求path={} 提交token={}", SaHolder.getRequest().getRequestPath(), StpUtil.getTokenValue()); }) .setError(e -> { return SaResult.error(e.getMessage()); }) .setBeforeAuth(obj -> { SaHolder.getResponse()
.setHeader("Access-Control-Allow-Origin", "*") .setHeader("Access-Control-Allow-Methods", "*") .setHeader("Access-Control-Allow-Headers", "*") .setHeader("Access-Control-Max-Age", "3600") ; SaRouter.match(SaHttpMethod.OPTIONS) .free(r -> System.out.println("--------OPTIONS预检请求,不做处理")) .back(); }) ; }
}
|
通过上述配置,最终解决了 跨域问题,同时,收获了一个经验,那就是 在项目集成了别的框架时,需要考虑是不是会影响原本正常的过程,导致原先的配置失效