【问题标题】:how to enable CORS filter in spring 4.2如何在 Spring 4.2 中启用 CORS 过滤器
【发布时间】:2023-04-04 20:12:01
【问题描述】:

我正在尝试从我的 Webstorm 应用程序向我的后端应用程序发送一个请求,它们都位于不同的端口,我在前端使用 angularJS,在后端使用 java spring 4.2.5。我尝试了各种方法,例如添加 cors 过滤器、cors 注释但是,在这样做之后我的错误是

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 天以来,我一直被困住,似乎无法使其正常工作。如果您可以指向我可以参考的博客/教程/视频

【问题讨论】:

    标签: java angularjs spring cors cross-domain


    【解决方案1】:

    Spring 它自己提供了启用 cors 的功能。请参考以下示例。

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

    【讨论】:

      【解决方案2】:

      要启用 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
                  });
      

      【讨论】:

      • 这是因为我的 http 请求不包含所需的源头吗?
      猜你喜欢
      • 2021-10-28
      • 2016-08-19
      • 2014-10-16
      • 1970-01-01
      • 2015-05-26
      • 2017-03-10
      • 2015-10-13
      • 2016-11-10
      相关资源
      最近更新 更多