在使用Angular和Spring Boot进行开发时,由于浏览器的同源策略限制,可能会遇到跨域问题。
解决这个问题的方法之一是在Spring Boot中添加一个跨域过滤器。
首先,创建一个名为CorsFilter的过滤器类,继承自OncePerRequestFilter:
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
response.setHeader("Access-Control-Max-Age", "3600");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
然后,在Spring Boot的主类中添加@ServletComponentScan
注解,以便识别并注册过滤器:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
最后,在Angular的服务端口上添加代理配置,将请求代理到Spring Boot的端口。在proxy.conf.json
文件中添加以下内容:
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
然后,在package.json
文件中的scripts
中添加以下内容:
"start": "ng serve --proxy-config proxy.conf.json"
重新启动Angular应用程序,跨域请求应该会成功。请确保将http://localhost:4200
(Angular的默认开发端口)添加到Angular应用程序的跨域白名单中。
这样,Angular和Spring Boot的跨域过滤器就会起作用了。