spring boot跨域问题

xiaoxiao2021-07-27  136

前后端分离的系统通常会出现跨域问题,最简单的办法是在每个controller上面添加注解:

@CrossOrigin(origins = "*")

但是,如果要对exception统一进行处理,使用@ControllerAdvice注解一个全局拦截器后,无法像controller一样添加注解就可以解决跨域问题,暂时还没有搜索到解决办法,期待哪位大神能给个提示。

package test.common.aop; import test.tips.ErrorTip; import test.common.exception.BizExceptionEnum; import io.jsonwebtoken.JwtException; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MaxUploadSizeExceededException; /** * 全局的的异常拦截器 * */ @ControllerAdvice @Slf4j public class GlobalExceptionHandler { /** * 拦截jwt相关异常 */ @ExceptionHandler(JwtException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorTip jwtException(JwtException e) { log.error("jwt exception: ", e); return new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage(), null); } /** * 拦截文件上传异常 */ @ExceptionHandler(MaxUploadSizeExceededException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorTip uploadException(MaxUploadSizeExceededException e) { log.error("file upload exception: ", e); return new ErrorTip(BizExceptionEnum.FILE_SIZE_ERROR.getCode(), BizExceptionEnum.FILE_SIZE_ERROR.getMessage(), null); } }

另外补充一个方法:覆写WebMvcConfigurationSupport中的addCorsMappings方法

@Configuration public class MvcConfig extends WebMvcConfigurationSupport { // 以下WebMvcConfigurerAdapter 比较常用的重写接口 // /** 解决跨域问题 **/ // public void addCorsMappings(CorsRegistry registry) ; // /** 添加拦截器 **/ // void addInterceptors(InterceptorRegistry registry); // /** 这里配置视图解析器 **/ // void configureViewResolvers(ViewResolverRegistry registry); // /** 配置内容裁决的一些选项 **/ // void configureContentNegotiation(ContentNegotiationConfigurer // configurer); // /** 视图跳转控制器 **/ // void addViewControllers(ViewControllerRegistry registry); // /** 静态资源处理 **/ // void addResourceHandlers(ResourceHandlerRegistry registry); // /** 默认静态资源处理器 **/ // void configureDefaultServletHandling(DefaultServletHandlerConfigurer // configurer); }

 

转载请注明原文地址: https://www.6miu.com/read-4823344.html

最新回复(0)