Angular、CORS 和 Spring 的问题 [英] Problems with Angular, CORS and Spring

查看:24
本文介绍了Angular、CORS 和 Spring 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于@RestController 和 AngularJS 的简单项目.我可以从 Angular 向 @RestController 发送 GET 请求,但我无法发送 POST 请求.我在浏览器控制台中出现错误:

<块引用>

XMLHttpRequest 无法加载 http://localhost:8080/add.Access-Control-Allow-Headers 不允许请求标头字段 Content-Type.

我的@RestController:

@RestController公共类 AngularController {//@自动连线//PhraseService 短语服务;Logger logger = LoggerFactory.getLogger(this.getClass());@RequestMapping(value = "/add", method = RequestMethod.POST)public void add(@RequestBody String str){logger.info("添加");logger.info(str);}@RequestMapping("/")公共无效角度控制器(){;logger.info("请求!");}}

这是我的 CORS 过滤器:

@Component公共类 SimpleCORSFilter 实现过滤器 {public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 抛出 IOException, ServletException {HttpServletResponse 响应 = (HttpServletResponse) res;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");response.setHeader("Content-Type", "application/json");chain.doFilter(req, res);}公共无效初始化(FilterConfig filterConfig){}公共无效销毁(){}}

我的 AngularJS 控制器:

function addController($scope, $http){$scope.url = 'http://localhost:8080/add';$scope.addPhrase = function(){$http.post($scope.url, {"data": $scope.value});}}

和 index.html:

<头><title>你好 AngularJS</title><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><script src="server.js"></script><身体><div ng-controller="addController"><表格><input type="text" np-model="value"/><button type="button" ng-click="addPhrase()">发送!</button></表单>

</html>

我试图用 header: "Content-Type": "application/json" 解决这个问题,但它给了我错误的请求错误.

解决方案

您也可以考虑使用即将推出的 Spring Framework 4.2 发布.有关详细信息,请参阅这篇博文.

默认情况下,它被配置为自动接受所有标头,因此只要您使用 CrossOrigin 注释或 Java 配置启用 CORS 支持,它就会立即工作.

I have a simple project based on @RestController and AngularJS. I can send GET requests from Angular to @RestController but i could not send POST request. I have an error in browser console:

XMLHttpRequest cannot load http://localhost:8080/add. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

My @RestController:

@RestController
public class AngularController {
    //@Autowired
  //  PhraseService phraseService;
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void add(@RequestBody String str){
        logger.info("Added");
        logger.info(str);

    }

    @RequestMapping("/")
    public void angularController(){;
        logger.info("Request!");
    }
}

Here is my CORS filter:

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        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");
        response.setHeader("Content-Type", "application/json");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

My AngularJS controller:

function addController($scope, $http){
    $scope.url = 'http://localhost:8080/add';
    $scope.addPhrase = function(){
        $http.post($scope.url, {"data": $scope.value});
    }
}

And index.html:

<!doctype html>
<html ng-app>
<head>
    <title>Hello AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script src="server.js"></script>
</head>

<body>
<div ng-controller="addController">
    <form>
    <input type="text" np-model="value"/>
        <button type="button" ng-click="addPhrase()">Send!</button>
    </form>
</div>
</body>
</html>

I tried to solve this problem with header: "Content-Type": "application/json" but it gave me Bad request error.

解决方案

You could also consider using the native CORS support available in the upcoming Spring Framework 4.2 release. See this blog post for more details.

By default, it is configured to automatically accept all the headers, so it should work as soon as you enable CORS support with CrossOrigin annotation or with Java config.

这篇关于Angular、CORS 和 Spring 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆