后端技术
解决spring boot 项目的跨域的问题
@Configuration public class SpringConfig {
@Bean public FilterRegistrationBean replaceTokenFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setDispatcherTypes(DispatcherType.REQUEST); registration.setFilter(new CrosFilter()); registration.addUrlPatterns("/*"); registration.setName("crosFilter"); registration.setOrder(1); return registration; } public class CrosFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers")); response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); if ("OPTIONS".equals(request.getMethod())) { response.setStatus(HttpStatus.NO_CONTENT.value()); } else { filterChain.doFilter(request, response); } } }
}