我的項目有一個奇怪的問題。我決定在Spring中編寫服務器應用程序,並使用AngularJS編寫前端程序。 在服務器端,我有一個簡單的控制器,從簡單的實體返回一些簡單的數據;)。它看起來像這樣:Spring&AngularJS - 與RESTful API的連接
@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(未找到)
我真的不知道該怎麼做。我希望在這兩個應用程序之間「交談」,但是我不能因爲這個原因。 如果有人能幫助我,我會非常感激。
它可能沒有什麼區別,但我看到你在http的配置中設置GET方法名稱。得到要求,當然你不需要這條線,它已經是GET – mindparse 2015-02-07 21:40:34
是的,我知道。此http的結構之間的變化不能解決問題。 – allocer 2015-02-07 21:54:18
如果您已經檢查過CORS不是問題,那麼您是否也仔細檢查過a)Spring應用程序正在偵聽8080以及b)沒有綁定的基本路徑(即某些/ foo/getAllProfiles) ? – h7r 2015-02-07 21:55:33