Solving cross-domain problems in SpringBoot_Cors cross-domain

Solve Cors cross-domain in SpringBoot

illustrate

  • Sometimes during the development stage, the front end will have cross-domain problems when sending http requests.
  • Recorded here are several methods for solving cross-domain problems in the SpringBoot project backend and development environment.
  • As long as the back-end code is not changed in the production environment, middleware can be used to solve cross-domain problems, such as Nginx's reverse proxy .

Method 1 Add @CrossOrigin annotation to class or method

// 加在类上就可以不用在该类里面的每个方法上面都加上该注解,
//		如果是只允许该方法允许跨域,那么可以只在该方法上面加上该注解
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";
    }
}

Method 2 Add a Cors filter configuration class [recommended]

// 在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);
    }
}

Method 3: Create a new CorsConfig configuration class, implement the WebMvcConfigurer interface, and override the addCorsMappings method

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);//单位为秒, 重新预检验跨域的缓存时间,表示该时间内,不用重新检验跨域
    }
}

Method 4: Implement the Filter interface and override the doFilter method

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() {
    
    }
}

Guess you like

Origin blog.csdn.net/qq_17847881/article/details/130481054