简体   繁体   中英

CORS request with AngularJS and Spring

I know there is a lot of information related to this kind of problem, but all the solutions I have read don't quite work for me.

So I'm going to leave my code here maybe you can figure out what's happening because I'm about to throw my computer through the window.

I'm getting this error with I click a button that hit an Ajax request to my rest server:

XMLHttpRequest cannot load http://localhost:8081/XXXXXXX. 
Request header field Access-Control-Allow-Origin is not allowed 
by Access-Control-Allow-Headers in preflight response.

Of course I already add the headers to the request on the client side (AngularJS):

all : function() {
    return $http({
        method : 'GET',
        url : url_base + '/XXXXXXXX',
        headers:{
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
            'X-Random-Header':'123123123'
        }
    });
}

On the server side, I add a filter in my web.xml file:

 <filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>
        filters.CORSFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

And I add a class implementing the filter interface:

package filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

@Component
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig arg0) throws ServletException {}

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletResponse response=(HttpServletResponse) resp;

        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");

        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {}

}

And the filter automatically adds the CORS headers to any response so I add my filter to any pattern.

That's the request and response headers, as you can see, they have the CORS headers, but I'm not quite sure what's going on.

Response Headers

Access-Control-Allow-Headers:x-requested-with
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length:0
Date:Sat, 28 Nov 2015 08:48:08 GMT
Server:Apache-Coyote/1.1
**Request Headers**
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8
Access-Control-Request-Headers:accept, access-control-allow-headers, access-control-allow-methods, access-control-allow-origin, x-random-header
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8081
Origin:http://127.0.0.1:8080
Referer:http://127.0.0.1:8080/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36

I read something about @CorsOrigin here through Rest Spring API, but I don't know I don't have that annotation available, so it's not compiling. Maybe I need to add a new specific library to my POM?

Don't put any header in your request with AngularJS.

Just add this filter in your web.xml, it's a filter: Explained here

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

That will tell Tomcat to allow the CORS request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM