SpringBoot : CORs Allow Custom Headers in Ajax calls

Points To Remember

Add the comma separated Headers (standard and Custom headers)

CORs Allow Custom Headers in Ajax calls

$.ajax({
  method : 'POST',
  url    : 'url',
  headers: {'Custom-Header-1':'h1','Custom-Header-2':'h2'},
  success: function(data){},
  error  : function(error){}

});
@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, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Custom-Header-1 , Custom-Header-2, X-Auth-Token");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}


  • Add the above filter in your spring boot application.
  • Add the comma separated headers at line 9 (highlighted)

No comments :

Post a Comment