CORS Filter not working as intended

后端 未结 1 925
别那么骄傲
别那么骄傲 2020-12-02 15:32

I am trying to send a request from my Webstorm application to my backend application, which both are at different ports, I am working with angularJS in the front end and jav

相关标签:
1条回答
  • 2020-12-02 16:06

    Your code and configuration looks good in general and I was able to run it on local environment. Please remove @Component annotation from your SimpleCORSFilter, because you use it as a plain Servlet Filter and it doesn't need to be a part of Spring context.

    UPD. Tomcat 7 has its own CORS filter implementation. You can check documentation and source code for more details. I have modified the headers to reflect its default configuration, should work as expected now.

    Since you are already using Spring and if you are using Spring 4.2 or higher, you dont need CorsFilter, but can simply annotate your controller method with CrossOrigin. Here is the excellent article on this, worth a read.

    Please also check nice resource which describes CORS configuration for different platforms.

    Here is my working example using plain Filter implementation:

    Controller:

    @Controller
    public class UserController {
    
        private static Logger log = Logger.getAnonymousLogger();
    
        @RequestMapping(
                value = "/register",
                method = RequestMethod.POST,
                consumes = "application/x-www-form-urlencoded")
        @ResponseBody
        public String register(@RequestParam(value = "user") String username,
                               @RequestParam(value = "password") String password) {
            log.info(username + " " + password);
            return "true";
        }
    
    }
    

    Filter:

    public class CorsFilter implements Filter {
    
        private static final Logger log = Logger.getAnonymousLogger();
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            log.info("Adding Access Control Response Headers");
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }
    

    Filter mapping in web.xml:

        <filter>
            <filter-name>cors</filter-name>
            <filter-class>com.udalmik.filter.CorsFilter</filter-class>
        </filter>
    
        <filter-mapping>
            <filter-name>cors</filter-name>
            <url-pattern>/register</url-pattern>
        </filter-mapping>
    

    JS to perform request from separate web app (JQuery):

    $(document).ready(function() {
        $('#buttonId').click(function() {
            $.ajax({
                type: "POST",
                url: "http://localhost:8080/register",
                success : function(data){
                    console.log(data);
                },
                data : {
                    user : 'test.user@acme.com',
                    password : 'password'
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题