我是AngularJS的新手,我無法通過REST更新對象。我正在使用PHP/Mysql後端(Slim Framework)。
我能夠檢索(GET),創建(POST)一個新的對象,但不能編輯(PUT)一個。下面的代碼:AngularJS - PUT方法不起作用(404錯誤)
我的表格:
<form name="actionForm" novalidate ng-submit="submitAction();">
Name: <input type="text" ng-model="action.name" name="name" required>
<input type="submit">
</form>
我的服務:
var AppServices = angular.module('AppServices', ['ngResource'])
AppServices.factory('appFactory', function($resource) {
return $resource('/api/main/actions/:actionid', {}, {
'update': { method: 'PUT'},
});
});
app.js
var app = angular.module('app', ['AppServices'])
app.config(function($routeProvider) {
$routeProvider.when('/main/actions', {
templateUrl: 'partials/main.html',
controller: 'ActionListCtrl'
});
$routeProvider.when('/main/actions/:actionid', {
templateUrl: 'partials/main.html',
controller: 'ActionDetailCtrl'
});
$routeProvider.otherwise({redirectTo: '/main/actions'});
});
controllers.js:
function ActionDetailCtrl($scope, $routeParams, appFactory, $location) {
$scope.action = appFactory.get({actionid: $routeParams.actionid});
$scope.addAction = function() {
$location.path("/main/actions/new");
}
$scope.submitAction = function() {
// UPDATE CASE
if ($scope.action.actionid > 0) {
$scope.action = appFactory.update($scope.action);
alert('Action "' + $scope.action.title + '" updated');
} else {
// CREATE CASE
$scope.action = appFactory.save($scope.action);
alert('Action "' + $scope.action.title + '" created');
}
$location.path("/main/actions");
}
}
在修身,在API/index.php文件,我已經得到了這些途徑和功能定義:
$app->get('/main/actions', 'getActions');
$app->get('/main/actions/:actionid', 'getAction');
$app->post('/main/actions', 'addAction');
$app->put('/main/actions/:actionid', 'updateAction');
當我創建一個新的「行動」,一切工作正常。但是,當我嘗試編輯現有的,我有這個錯誤:
PUT http://project.local/api/main/actions 404 Not Found
動作不更新(雖然會顯示警告信息「行動XXX更新」)
它是一個問題與我的routeProvider設置?我猜PUT URL錯過在年底的ID ...
我準確的,如果我嘗試模擬與POSTMan-Chrome-Extension例如PUT請求,一切運作良好(PUT http://project.local/api/main/actions/3返回預期的數據)
你的代碼中至少有一個不匹配的地方:在資源定義中你的url是'/ api/main/actions /:actionid',但你的調用說** app/main/... **。警報消息應放入資源的成功回調中。如果你把它放在它後面,它和xhr請求之間沒有邏輯關係。 – Narretz
@Narretz,你是對的成功回調,謝謝你的提示。然而,我的url似乎對我來說是正確的:我的php後端(slim框架)位於/ api下(路徑在/api/index.php中定義),而網站位於/ app下。這種架構受到https:// github的啓發。com/Narretz /角地窖 – bsfoo116
有趣的是,看到地窖仍然很受歡迎。 ;)這真的很難從遠處調試,但是資源中的url和你粘貼的返回404的url之間仍然存在差異,具體來說第一個是** api **和第二個**應用程序** ,即xhr請求正在應用程序文件夾中查找服務器。如果不是拼寫錯誤,那麼問題一定在某處。 OMG! – Narretz