简体   繁体   中英

Angular/Express/Mongoose PUT method Inline Table Issues

So I've been ripping my hair out for a few days now. I am not sure why my PUT request in my angular/node train schedule app is not working. GET/POST/DELETE all work and I can update in POSTMAN but when I do inline editing and try to update from the front end I get a 404 not found even though everything appears to be right. I'm using mongoose to manage mongoDB and like I said it all works in postman. Anyways here is my code.

MAIN CONTROLLER

  angular.module('MainCtrl', []).controller('MainController', ['$scope',       '$parse', 'Train', function ($scope, $parse, Train) {
  $scope.globalConfiguration = {

    newField: {},
    removeItem: function removeItem(row) {
        var index = $scope.trains.indexOf(row);
        console.log(index);
        if (index !== -1) {
            Train.delete({
                id: $scope.trains[index]._id
            }, function () {});
            $scope.trains.splice(index, 1);
        }
    },

    updateTrain: function updateTrain(row) {
        var index = $scope.trains.indexOf(row);
        console.log(index);
        console.log($scope.trains[index]._id);
        if ($scope.globalConfiguration.editing !== false) {
            $scope.trains[$scope.globalConfiguration.editing] = $scope.globalConfiguration.newField;
            Train.update({
                id: $scope.trains[index]._id,
                index
            });

            $scope.globalConfiguration.editing = false;

        }
    },
    edit: function edit(row) {
        var index = $scope.trains.indexOf(row);
        $scope.globalConfiguration.editing = index;
        $scope.globalConfiguration.newField = angular.copy(index);
    },
    cancel: function (index) {

        if ($scope.globalConfiguration.editing !== false) {
            $scope.trains[$scope.globalConfiguration.editing] = $scope.globalConfiguration.newField;
            $scope.globalConfiguration.editing = false;
        }
    }
};

ANGULAR SERVICE

 angular.module('TrainService', []).factory('Train', function($resource) {
   return $http.get('api/trains');
        return $resource('/api/trains');
return $resource('api/trains/:id', { id: '@_id' }, {
        'update': { method:'PUT' },
        'saveData': { method: 'POST', isArray: false}
      });
});

ROUTES.JS NODE

var Train = require('./model/train');
app.get('/api/trains', function (req, res) {
    // use mongoose to get all trains in the database
    Train.find(function (err, trains) {

        // if there is an error retrieving, send the error. 
        // nothing after res.send(err) will execute
        if (err)
            res.send(err);

        res.json(trains); // return all nerds in JSON format
    });
});
// Get Train By id
app.get('/api/trains/:id', function (req, res) {

    Train.findById(req.params.id, function (err, train) {
        if (err)
            res.send(err);
        res.json(train);

    });
});
// Update Trains 
app.put('/api/trains/:id', function (req, res) {
    Train.findByIdAndUpdate(req.params.id, req.body, function (err, train) {
        if (err)
            res.send(err);

        res.json(train);

    });
});

// route to handle creating trains goes here (app.post)
app.post('/api/trains', function (req, res) {
    //Create Trains
    Train.create(req.body, function (err, train) {
        if (err)
            res.send(err);

        res.json(train);

    });

});



// route to handle delete goes here (app.delete)
app.delete('/api/trains/:id', function (req, res) {
    Train.findByIdAndRemove(req.params.id, req.body, function (err, train) {
        if (err)
            res.send(err);

        res.json(train);

    });

});

VIEW HTML

<tr ng-repeat="row in displayedCollection | orderBy:'RUN_NUMBER' | unique:'RUN_NUMBER' ">
        <td>{{row.TRAIN_LINE | uppercase}}</td>
        <td>{{row.RUN_NUMBER | uppercase}}</td>
        <td>{{row.ROUTE_NAME | uppercase}}</td>
        <td><span ng-hide="editMode">{{row.OPERATOR_ID | uppercase}}</span>
            <input name="row.OPERATOR_ID" ng-show="editMode" type="text" ng-model="row.OPERATOR_ID">
        </td>
        <td>
            <button class="btn btn-sm btn-success" ng-show="editMode" ng-click="globalConfiguration.updateTrain(row); editMode = false;"><i class="glyphicon glyphicon-ok"></i>
            </button>
            <button class="btn btn-sm btn-warning" ng-show="editMode" ng-click="editMode = false; globalConfiguration.cancel()"><i ng- class="glyphicon glyphicon-remove"></i>
            </button>
            <button class="btn btn-sm btn-info" ng-hide="editMode" ng-click="editMode = true; globslConfiguration.edit(row)"><i class="glyphicon glyphicon-pencil"></i>
            </button>
            <button ng-click="globalConfiguration.removeItem(row)" class="btn btn-sm btn-danger"><i class="glyphicon glyphicon-remove-circle"></i>
            </button>

        </td>
    </tr>

I tried to keep it minimal in terms of putting only the things I think are relevant to my issue but the rest of the code is here.

https://github.com/chmaltsp/Trains-Exercise

Appreciate the help!!!

Easiest thing you can do is simply change your PUT request to listen on /api/trains and instead of req.params.id , capture req.body.id . Like so:

// Update Trains 
app.put('/api/trains', function (req, res) {
    Train.findByIdAndUpdate(req.body.id, req.body, function (err, train) {
        if (err)
            res.send(err);

        res.json(train);

    });
});

More detail as to why this update would work:

Angular's $resource will convert GET requests to URL-based params like so:

/api/trans/<id_goes_here>

All other requests pass parameters into the req.body

Take a look at your PUT listener:

app.put('/api/trains/:id', function (req, res) {
    Train.findByIdAndUpdate(req.params.id, req.body, function (err, train) {
    ...

Notice you're expecting a param titled req.params.id . This won't work for PUT requests coming from Angular's $resource . You're getting a 404 error because Angular is trying to do a PUT request to /api/trains - not /api/trains/<id_goes_here>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM