在Spring Boot中配置跨域请求可以通过以下几种方式:
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class MyController {
// ...
}
注解中的origins属性指定允许跨域请求的来源,可以使用通配符*表示允许所有来源。maxAge属性指定预检请求的有效期,单位为秒。
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials","true");
chain.doFilter(req, res);
}
// ...
}
以上是几种常用的Spring Boot跨域配置方法,根据具体的需求选择适合的方式来配置跨域请求。