我想從Angular-JS頁面的Java後端調用REST服務。我可以成功獲取GET數據,但無法調用@POST資源。
例如在Java後端這裏是我的RESTful服務方法 -
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public User create(User user) {
User usr1 = new User();
usr1.setId(3);
usr1.setFirstName("John");
usr1.setLastName("Paul");
return usr1;
}
在AngularJS部分這裏是服務工廠:
var app = angular.module('app', ['ngResource']);
app.factory('UsersFactory', function ($resource) {
return $resource('http://localhost:8080/demoApp/service/users', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST'}
})
});
這裏是AngularJS控制器:
app.controller('userCreationCtrl', ['$scope', 'UsersFactory', '$location',
function ($scope, UsersFactory, $location) {
$scope.createNewUser = function() {
UsersFactory.create($scope.user);
}
}]);
錯誤顯示在Chrome瀏覽器的Javascript控制檯 -
XMLHttpRequest cannot load http://localhost:8080/demoApp/service/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
它是一個CORS問題,但你說GET可以工作,所以你必須已經部分安裝了CORS。我遇到了同樣的問題(CORS在GET請求中工作,但不是在POST請求中),我使用的是第三方CORS過濾器,我無法正常工作。你在使用哪臺服務器?如果它是Tomcat,它有它自己的CORS過濾器,它工作得非常好。 – Gimby