Spring & AngularJS - 连接 RESTful API

Spring & AngularJS - connection with RESTful API

我的项目有一个奇怪的问题。我决定用 Spring 编写服务器应用程序,并用 AngularJS 编写前端。 在服务器端,我有一个简单的控制器,其中 return 一些来自简单实体的简单数据;)。它看起来像这样:

@RestController
public class ApiController
{
    @RequestMapping( value = "/getAllProfiles", method = RequestMethod.GET)
    public Entity getEntity()
    {
        Entity e = new Entity();
        e.setName( "myname" );
        return e;
    }
}

在正面,我有一个 Angulars 控制器,看起来像:

var app = angular.module('app', []);

app.config(function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;   
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

app.controller('Hello', function ($scope, $http) {
    $http.get({
        method: 'GET',
        url: 'http://localhost:8080/getAllProfiles'
    }).success(function (data) {
        console.log('success', data)
        $scope.greeting = data;
    }).error(function(){
        console.log("something goes wrong");
    });
})

和html文件:

<html ng-app="app">
<head>
    <title>Hello AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
    <script src="view1.js"></script>
</head>
<body>
<div ng-controller="Hello">
    <p>The content is {{greeting.name}}</p>
</div>
</body>
</html>

当我启动服务器时,我连接到 localhost:8080/getAllProfiles,一切正常。我收到 JSON 这样的 {"name":"myname"}。但是,当我尝试从 Angular 端执行相同操作时,我收到 The content is - 来自服务器的空数据,当然,错误函数正在控制器中调用。我认为这可能是 CORS 问题,但我在服务器端和 Angular 端添加了过滤器,但没有帮助。 js 控制台(我正在使用 Chrome)显示:无法加载资源:服务器响应状态为 404(未找到)

我真的不知道该怎么办。我想在这两个应用程序之间使用 "to talk",但因此我做不到。 如果有人能帮我解决这个问题,我将不胜感激。

如果 CORS 是本地主机上的问题,那么您可以使用 grunt-connect-proxy。 在你的 g运行t 文件中定义:

proxies: [
                {
                    context: '/',
                    host: '127.0.0.1',
                    port: 8080,
                    https: false,
                    xforward: false
                }
            ]

不要忘记将 connext 代理任务添加到您的任务中。 网站上的一切都解释得很清楚。 这将解决本地主机中的跨域问题。 然后你可以在你的控制器中调用你的服务器:

$http.get({
        method: 'GET',
        url: '/getAllProfiles'
    })

它会起作用,因为 g运行t 会 运行 代理您的 angular 应用程序端口。

顺便说一句。 您是否尝试过通过单元测试来测试您的 angular 逻辑? 使用 $httpbackend 模拟与您的 Spring 应用程序完全相同的后端,您将看到结果。

好的,问题终于解决了。谢谢 cyan 的帮助,Grunt 是一个解决方案。

我想为不想阅读本主题所有内容的人介绍此解决方案。 ;) 我想从一些 Angular 应用程序连接到我的 Spring REST API(2 个独立的应用程序),但由于本地主机上的代理问题,我无法这样做。我已经为我的 Angular 应用程序安装了一个 Grunt,对其进行了配置,启动了服务器并尝试从中获取数据。它脱落了。 当然,还需要服务器端的 CORS 过滤器。它们在此处描述 https://spring.io/guides/gs/rest-service-cors/

我使用的教程对我有帮助: http://www.hierax.org/2014/01/grunt-proxy-setup-for-yeoman.html http://fettblog.eu/blog/2013/09/20/using-grunt-connect-proxy/ 和来自青色的 github 的 link。