我目前有一个MEAN堆栈项目,我正在尝试获取更新工作的路由。保存工作正常。
基本上在我的角度控制器中,我有以下范围方法,其中staff
是在表单提交时发送的对象:
$scope.updateStaff = function(staff) {
$scope.submitted = true;
if (form.$valid) {
staffActionService.update({ id: staff._id }, staff)
.then(function () {
$scope.success = true;
console.log("successful");
})
.catch(function (err) {
var err = err.data;
$scope.errors = {};
angular.forEach(err.errors, function (error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
}
}
另外,我有一个工厂方法,基本上使用$resource
进行客户端路由:
angular.module('xxx')
.factory('staffActionService', function ($resource) {
return $resource('/api/staffs/:id/:controller',
{ id: '@_id' },
{ 'update': { method:'PUT' } }
);
});
});
我的服务器端路由设置如下
var express = require('express');
var controller = require('./staff.controller');
var router = express.Router();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.create);
router.put('/:id/staff', controller.update);
router.patch('/:id', controller.update);
router.delete('/:id', controller.destroy);
module.exports = router;
但由于某种原因,我的服务器端没有被击中
任何想法已经尝试了一些路由但没有快乐的事情
干杯
答案 0 :(得分:0)
看起来您正在调用PATCH方法的路由,但是在客户端上使用PUT方法,这将产生404.
您可以通过以下三种方式之一解决此问题:
您可以通过让PUT路由响应' /:id'来解决它:
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.create);
router.put('/:id/staff', controller.update);
router.put('/:id', controller.update); // add this
router.patch('/:id', controller.update);
router.delete('/:id', controller.destroy);
module.exports = router;
或者您可以通过定义':控制器'来在角度控制器中修复它。来自您设置的$ resource工厂:
staffActionService.update({ id: staff._id, controller: 'staff' }, staff)
或者您可以通过将方法更改为PATCH来修复$ resource工厂:
angular.module('xxx')
.factory('staffActionService', function ($resource) {
return $resource('/api/staffs/:id/:controller', { id: '@_id' }, {'update': {method:'PATCH'}})
});
注意:不要结合上面的例子,只使用一个!