1
我正在嘗試實現一個簡單的編輯功能,它不起作用。我刪除並獲得工作。我在收到請求時一直收到500錯誤。我試過findIdAndUpdate,我也試過FindOne。我得到的錯誤是它無法加載資源。但是,如果我做了一個獲取請求,它工作正常。如果有差別,GET請求也返回一個304Mongoose,Angular,Express PUT將不起作用
如果我捲曲發送請求我得到TypeError: Cannot read property 'id'
控制器和服務
app.factory('gameService', function($resource){
return $resource('/api/games/:id', {id:'@id'},
{'update': {method:'PUT'}}
);
});
app.controller("gameController", function($scope, $http, gameService){
$scope.games = [];
$scope.newGame = {name: '', platform: ''};
$scope.editMode = false;
$scope.games = gameService.query();
$scope.edit = function(game){
$scope.editMode = true;
$scope.newGame = gameService.get({id: game._id});
};
$scope.update = function(){
gameService.update({id: $scope.newGame._id}, function(response){
$scope.games = gameService.query();
$scope.newGame = {name: '', platform:''};
});
$scope.editMode = false;
};
});
API /快速/貓鼬
router.put('/games/:id', function(req, res, next) {
Game.findById(req.parms.id, function (err, game) {
if (err) {
return res.send(err);
}
game.name = req.body.name;
game.platform = req.body.platform;
game.save(function(err){
if (err) {
return res.send(err);
}
res.json({message:'Game Updated'});
});
});
});
HTML
<input required type="text" placeholder="Game Name" ng-model="newGame.name" /> <br/><br/>
<input required type="text" placeholder="Platform" ng-model="newGame.platform" /> <br/><br/>
<input class="button" type="submit" value="Post" ng-click="post()" ng-hide="editMode" />
<input class="button" type="submit" value="Update" ng-click="update()" ng-show="editMode"/>
型號
var mongoose = require ('mongoose');
var GameSchema = new mongoose.Schema({
name: String,
platform: String
});
mongoose.model ('Game', GameSchema);
修正了這個問題。現在我有一個新問題。 game.save正在清除名稱和platofmr字段。所以它會出現req.body.name不正確 – CodyK
我明白了,謝謝。 – CodyK