SpringBoot如何解决跨域问题
第一种方法:
import org.springframework.context.annotation.Configuration;
import org.springframework.web. servlet.config.annotation.CorsRegistry;
import org.springf ramework.web . servlet.config.annotation. webMvcConfigurer;
@Configuration
public class CorsConfig implements webMvcConfigurer {
0verride
public void addCorsMappings ( CorsRegistry registry) {
registry.addMapping( " /**")
.allowed0rigins( "*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge ( 3600 )
.allowedHeaders( "*" );
}
}
第二种方法:
import org.springframework.context.annotation.Configuration;
import javax.servlet.* ;
import javax.servlet.annotation. webFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@webFilter(filterName = "CorsFilter " )
@Configuration
public class CorsFilter implements Filter {
Override
public void doFilter(ServletRequest req,ServletResponse res,FilterChainchain ) throws 1OException,servletException {
HttpServletResponse response = ( HttpServletResponse) res;
response.setHeader( "Access-Control-Allow-Origin" , "*" );
response.setHeader( "Access-Control-Allow-Credentials" ,"true" );
response.setHeader( "Access-Control-Allow-Methods ","POST,GET,PATCH,DELETE,PUT");
response.setHeader( "Access-Control-Max-Age", "3600" );
response.setHeader( "Access-Control-Allow-Headers","Origin,X-Requested-with,Content-Type,Accept " );
chain.doFilter( req,res );
}
}
第三种方法:
使用@CrossOrigin注解:
public class GoodsController {
@Cross0rigin(origins = "http: / /localhost: 4000")
@GetMapping( "goods-url" )
public Response queryGoodsWithGoodsUrl(@RequestParam String goodsUrl) throwsException {}