后端如何处理跨域

  1. 使用@CrossOrigin注解:
    可以为Controller中的方法添加@CrossOrigin注解来允许来自特定源(或所有源)的跨域请求。例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RestController
    public class MyController {

    @RequestMapping("/hello")
    @CrossOrigin(origins = "http://localhost:8080")
    public String hello() {
    return "Hello World!";
    }
    }
  2. 配置WebMvcConfigurer:
    在WebMvcConfigurer中配置addCorsMappings()方法,它会将跨域配置应用于整个应用程序。例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Configuration
    public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
    .allowedOrigins("http://localhost:8080")
    .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
    }
  3. 使用Filter过滤器:
    实现一个CorsFilter类并继承OncePerRequestFilter类。然后在doFilterInternal方法中设置跨域头。例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

    response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "1800");

    filterChain.doFilter(request, response);
    }
    }