SpringBoot中解决跨域问题_Cors跨域

SpringBoot中解决Cors跨域

说明

  • 有时在开发阶段,前端在发送http请求的时候会存在跨域问题,
  • 这里记录在SpringBoot项目后端,开发环境解决跨域问题的几种方法,
  • 生产环境不改动后端代码的前提,可以使用中间件来解决跨域问题,如Nginx的反向代理

方式1 类或方法上加 @CrossOrigin 注解

// 加在类上就可以不用在该类里面的每个方法上面都加上该注解,
//		如果是只允许该方法允许跨域,那么可以只在该方法上面加上该注解
package com.project.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
//@CrossOrigin   // 加在类上,类里面的每个方法都允许跨域
public class TestController {
    
    
    
    @GetMapping("/list")
    @CrossOrigin  // 仅控制该方法支持跨域
    public String list(){
    
    
        return "helloword";
    }
}

方式2 添加一个Cors过滤器的配置类 [ 推荐使用 ]

// 在config包下,新建一个CORS过滤器的配置类,CorsConfig类,如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    
    

    @Bean
    public CorsFilter corsFilter(){
    
    
        CorsConfiguration corsConfiguration=new CorsConfiguration();
        //允许跨域的主机地址,*表示所有都可以
        corsConfiguration.addAllowedOrigin("*");
        //允许跨域的请求头
        corsConfiguration.addAllowedHeader("*");
        //允许跨域的请求方法
        corsConfiguration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsFilter(source);
    }
}

方式3 新建CorsConfig配置类,实现WebMvcConfigurer接口,重写addCorsMappings方法

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 corsRegistry) {
    
    
        corsRegistry.addMapping("/**")
                    .allowedOrigins("*")//允许跨域的主机地址,*表示所有都可以
                    .allowedHeaders("*")//允许跨域的请求头
                    .allowedMethods("GET","POST","PUT","DELETE","HEAD","OPTIONS")//允许跨域的请求方法
                    .allowCredentials(true)//是否允许携带cookie,true表示允许
                    .maxAge(3600);//单位为秒, 重新预检验跨域的缓存时间,表示该时间内,不用重新检验跨域
    }
}

方式4 实现Filter接口,重写doFilter方法

import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsConfig implements Filter {
    
    

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
    
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");	//是否允许携带cookie,true表示允许
        res.addHeader("Access-Control-Allow-Origin", "*");			//允许跨域的主机地址,*表示所有都可以
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");//允许跨域的请求方法
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");	//允许跨域的请求头
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
    
    
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    }

    @Override
    public void destroy() {
    
    }
}

猜你喜欢

转载自blog.csdn.net/qq_17847881/article/details/130481054