在Spring Boot中处理跨域请求可以通过以下方式实现:
@RestController
public class MyController {
@CrossOrigin(origins = "http://localhost:8080")
@GetMapping("/example")
public String example() {
return "Hello, World!";
}
}
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST")
.allowedHeaders("Authorization")
.allowCredentials(true);
}
}
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
res.setHeader("Access-Control-Allow-Methods", "GET, POST");
res.setHeader("Access-Control-Allow-Headers", "Authorization");
res.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(request, response);
}
}
以上是在Spring Boot中处理跨域请求的几种常见方法,根据具体情况选择合适的方式来实现跨域请求的处理。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。