您好,登錄后才能下訂單哦!
1、第一種:
public class CorsFilter extends OncePerRequestFilter { static final String ORIGIN = "Origin"; protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String origin = request.getHeader(ORIGIN); response.setHeader("Access-Control-Allow-Origin", "*");//* or origin as u prefer response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "content-type, authorization"); if (request.getMethod().equals("OPTIONS")) response.setStatus(HttpServletResponse.SC_OK); else filterChain.doFilter(request, response); } } @Bean public CorsFilter corsFilter() throws Exception { return new CorsFilter(); } http .addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class) .headers() .cacheControl();
2、第二種:
@Configuration public class CorsConfig { @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 設置你要允許的網站域名,如果全允許則設為 * config.addAllowedOrigin("http://localhost:4200"); // 如果要限制 HEADER 或 METHOD 請自行更改 config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); // 這個順序很重要哦,為避免麻煩請設置在最前 bean.setOrder(0); return bean; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。