在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跨域配置方法,根據具體的需求選擇適合的方式來配置跨域請求。