简体   繁体   English

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

[英]how to enable CORS filter in spring 4.2

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 java spring 4.2.5 in backend. 我正在尝试将Webstorm应用程序的请求发送到后端应用程序,这两个应用程序都位于不同的端口,我在前端使用angularJS,在后端使用Java spring 4.2.5。 I have tried various things like adding cors filter,cors annotation However, after doing this my error, being 我尝试了各种操作,例如添加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.

The angularJS controller looks like 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
            });
        }
    }
});

The spring controller looks like 弹簧控制器看起来像

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

I tried adding CORS filter but nothing seems to work. 我尝试添加CORS过滤器,但似乎无济于事。 Not sure if it is picked up by the app. 不知道它是否被应用程序拾取。 I mean if its in the config path. 我的意思是如果它在配置路径中。

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() {
    }
}

The web.xml looks like 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>

This is what the http call looks like. 这就是http调用的样子。 It doesnt contain allowed access headers 它不包含允许的访问标头

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

I would really appreciate if someone could guide me. 如果有人可以指导我,我将不胜感激。 I been stuck since last 5 days cant seem to get this working. 由于过去5天似乎无法正常工作,我被困住了。 if you could point to a blog/tutorial/video which i can refer to 如果您可以指向我可以参考的博客/教程/视频

Spring it self provide feature to enable cors. 弹簧本身提供启用cors的功能。 Please refer below example. 请参考以下示例。

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

To enable CORS, annotate your request method with 要启用CORS,请使用注释您的请求方法

@CrossOrigin(origins = "http://localhost:63342")

Have a look at the Spring documentation of CORS 看看CORSSpring文档

UPDATE UPDATE

I had the same problem in my application, removed CrossOrigin annotation in request method and added below in angular service js 我在我的应用程序中遇到了同样的问题,在请求方法中删除了CrossOrigin注释,并在以下角度服务js中添加了它

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

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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