简体   繁体   English

Angular / Express / Mongoose PUT方法内联表问题

[英]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. 我不确定为什么我的角度/节点火车时刻表应用程序中的PUT请求无法正常工作。 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. GET / POST / DELETE都能正常工作,我可以在POSTMAN中进行更新,但是当我进行内联编辑并尝试从前端进行更新时,即使一切似乎正确,我也找不到404。 I'm using mongoose to manage mongoDB and like I said it all works in postman. 我正在使用猫鼬来管理mongoDB,就像我说的那样,所有这些都可以在邮递员中使用。 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 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 查看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 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 . 您最容易做的就是更改您的PUT请求以监听/api/trains ,而不是req.params.id ,而是捕获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: Angular的$ resource将GET请求转换为基于URL的参数,如下所示:

/api/trans/<id_goes_here>

All other requests pass parameters into the req.body 所有其他请求将参数传递到req.body

Take a look at your PUT listener: 看一下您的PUT侦听器:

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 . 注意,您期望使用名为req.params.id的参数。 This won't work for PUT requests coming from Angular's $resource . 这对于来自Angular的$ resource的 PUT请求不起作用。 You're getting a 404 error because Angular is trying to do a PUT request to /api/trains - not /api/trains/<id_goes_here> 您收到404错误,因为Angular试图向/api/trains发出PUT请求-而不是/api/trains/<id_goes_here>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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