如何在Spring 4.2中启用CORS过滤器

时间:2016-06-19 03:41:59

标签: java angularjs spring cors cross-domain

我正在尝试从我的Webstorm应用程序向我的后端应用程序发送请求,这两个应用程序位于不同的端口,我正在使用前端的angularJS和后端的java spring 4.2.5。我尝试了各种各样的事情,比如添加cors过滤器,cors annotation但是,这样做后我的错误就是

XMLHttpRequest cannot load http://localhost:8081/appUser. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 404.

angularJS控制器看起来像

registerController.factory('registerFactory', function(){
    return {
        getClassification:function($http,tempString){
            //TODO add URL
            var url = "http://localhost:8081/example?eg="+tempString
            return $http({
                method: 'POST',
                url: url
            });
        }
    }
});

弹簧控制器看起来像

@RequestMapping(value = "/example", method = RequestMethod.POST)
@ResponseBody
public String postAppUser(@RequestParam String eg) throws JsonProcessingException {
        return "ok yes ";           
}

我尝试添加CORS过滤器,但似乎没有任何效果。不确定它是否被应用程序选中。我的意思是如果它在配置路径中。

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

@Component
public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}

web.xml看起来像

<web-app>
  <display-name>Archetype Created Web Application</display-name>


  <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.myApp.security.CORSFilter</filter-class>
    </filter>

  <filter-mapping>
      <filter-name>cors</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

这就是http调用的样子。它不包含允许的访问标头

Request URL:http://localhost:8081/appUser
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:8081
Response Headers
view source
Content-Length:965
Content-Type:text/html;charset=utf-8
Date:Sun, 19 Jun 2016 03:43:40 GMT
Server:Apache-Coyote/1.1
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8081
Origin:http://localhost:63342

如果有人能指导我,我真的很感激。自从过去5天以来我一直被困住似乎无法让这个工作。如果你可以指向我可以参考的博客/教程/视频

2 个答案:

答案 0 :(得分:0)

Spring它自己提供启用cors的功能。请参考下面的例子。

https://spring.io/guides/gs/rest-service-cors/

答案 1 :(得分:0)

要启用CORS,请使用

注释您的请求方法
@CrossOrigin(origins = "http://localhost:63342")

查看Spring documentation of CORS

<强>更新

我在我的应用程序中遇到了同样的问题,在请求方法中删除了CrossOrigin注释,并在角度服务js中添加了下面

delete $http.defaults.headers.common['X-Requested-With'];

return $http({
                method: 'POST',
                url: '/example'/ + '?eg=' + tempString
            });