Thursday, September 28, 2017

Spring boot CORS Filter not working with AngularJS

I have created a SpringBoot application which has an AngularJS front-end and I am not using any Spring Security modules.

I have added the @CrossOrigin annotation in my controller as follows

@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RestController
public class MyController {
   public static final Logger logger = LoggerFactory.getLogger(MyController.class);
   .....
   .....

I have also created a CORS filter as shown below.

@Component
public class CORSFilter implements Filter {

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", "POST, GET, PUT, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}
public void destroy() {}

}

I am getting the following error for OPTIONS in my angularJS front-end

XMLHttpRequest cannot load http://localhost:8080/abc/books/. Response for preflight has invalid HTTP status code 401 (edited)

[12:10] 
zone.js:2744 OPTIONS http://localhost:8080/abc/books/ 401 ()

My SpringBoot app works fine with PostMan and this preflight error happens when I use Chrome. How can I fix it?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/spring-boot-cors-filter-not-working-with-angularjs/
via @lzomedia #developer #freelance #web

No comments:

Post a Comment