The cross-domain issues springboot

Cross-domain issues springboot of, if not careful, likely to cause mistake, this springboot version 2.13

Front-end error message:

Access to XMLHttpRequest at 'http://localhost:8080/user/loginOn' from origin 'http://localhost:8082' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The first: there is in each Controller, add comments: @CrossOrigin

 

import javax.validation.Valid;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController{

 

The method can also be coupled in, so that for example, such a method for the specific

  @CrossOrigin
    @ApiOperation(value = "用户登录",notes = "")
    @PostMapping("/loginOn")
    public ResponseMessage loginOn(@RequestBody @Valid UserReq userReq){

Each Controller also wrote a lot of trouble.

 

The second: to achieve WebMvcConfigurer interface for cross-domain support in the interface

Used to be able to inherit WebMvcConfigurerAdapter, springboot2.x version has its @Deprecated

We implement the interface directly:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 跨域支持
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600 * 24);
    }

However, using this method, I met a pit today, I am ready to intercept the user's request interceptor inside

@Component
 public  class RequestInterceptor the implements HandlerInterceptor from {
    @Override
     public Boolean The preHandle (the HttpServletRequest Request, Response the HttpServletResponse, Object Handler) throws Exception { 
       Object loginUser = Request.getSession () the getAttribute ( "token");. 
        IF (loginUser == null) { 
        // custom exception class, where an exception is thrown, to capture global exception handling throw new ServiceException ( "do not have permission, please login!"); } the else { return to true; }
} @Override public void postHandle (the HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }

Capture global exception classes:

@RestControllerAdvice
public class GlobleExceptionHandler {
    @ExceptionHandler(value = ServiceException.class)
    public ResponseMessage caughtException(ServiceException e){

        return new ResponseMessage(e.getMsg());
    }
}
ResponseMessage custom message class unified response:
@Data
public class ResponseMessage {
    private Integer Code;
    private String msg;
    private Integer count;
    private Object data;

    public ResponseMessage(Object data) {
        this.data = data;
    }

    public ResponseMessage(String msg) {
        this.msg = msg;
    }

    public ResponseMessage(Integer code, String msg) {
        Code = code;
        this.msg = msg;
    }

    public ResponseMessage(Integer code, String msg, Integer count) {
        Code = code;
        this.msg = msg;
        this.count = count;
    }

    public ResponseMessage(Integer code, String msg, Integer count, Object data) {
        Code = code;
        this.msg = msg;
        this.count = count;
        this.data = data;
    }

    public static  ResponseMessage success(String msg){
        return new ResponseMessage(200,msg);
    }

    public static ResponseMessage fail(Integer code,String msg){
        return new ResponseMessage(code,msg);
    }
}
ResponseMessage

Through this process we found that the front has been reported abnormal cross-domain problem, this time with the third method

Third: Use CorsFilter Filters:

Write a MyCorsConfig configuration class

@Configuration
public class MyCorsConfig {

    @Bean
    public CorsFilter corsFilter() {

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = newUrlBasedCorsConfigurationSource (); 
        source.registerCorsConfiguration ( "/ **" , corsConfiguration); 
        FilterRegistrationBean the bean = new new FilterRegistrationBean ( new new CorsFilter (Source));
         // set the order of filters 
        bean.setOrder (0 );
         return  new new CorsFilter (Source) ; 
    } 
}

Final settlement of cross-domain issues this demo.

 

Guess you like

Origin www.cnblogs.com/tdyang/p/12141816.html