使用route param在API PUT调用上获取404错误

时间:2015-03-11 18:22:59

标签: angularjs node.js express mean-stack angular-http

这是我想在我的 Express 应用中点击的API网址:

// Dashboard API to update account
app.post('/api/accounts/:id', accountsController.update);

enter image description here

我的帐户工厂的完整帐户模块,然后是以下具体说明:

(function() {

    var app = angular.module('app-accounts',
    ['ngAnimate', 'ngResource', 'account-directives'])

    .controller('AcctCtrl',
        ['$scope', '$resource', 'Accounts',
        function($scope, $resource, Accounts) {

        var vm = $scope;
            vm.$parent.modal = false;

        var Account = $resource('/api/accounts');

        // Open the edit account modal:
        this.editAccount = function(id, label, address) {
            console.log(id);
            vm.dash.modal = true;
            Accounts.modalEditAccount(vm.dash, id, label, address);
        };

        vm.dash.updateAccount = function(i) {
            console.log(i);
            // Call Update method from Accounts factory
            Accounts.update(i, $scope.new_label, $scope.new_address);
        }
    }])

    // Accounts factory (open edit model, get all, update, remove):
    .factory('Accounts', ['$http', '$resource', function($http, $resource) {

        var accountsFactory = {};

        accountsFactory.modalEditAccount = function(vm, id, label, address) {
            vm.modal_edit_account = true;
            vm.acct_id = id;
            vm.acct_label = label;
            vm.acct_address = address;
            vm.save_btn_text = 'save';
        };

        // Get all the accounts
        accountsFactory.all = function() {
            return $http.get('/api/stuff');
        };

        // Updates an account
        accountsFactory.update = function(id) {
            return $http.put('/api/accounts/'+id);
        };

        // Delete account
        accountsFactory.remove = function(id) {
            return $http.delete('/api/accounts/'+id);
        };

        return accountsFactory;

    }]);

})();

updateAccounts函数获取所选帐户的id并将其传递到Accounts工厂的更新功能中:

vm.dash.updateAccount = function(i) {
    console.log(i);
    // Call Update method from Accounts factory
    Accounts.update(i, $scope.new_label, $scope.new_address);
}

接下来在我的Accounts工厂内,这是PUT / UPDATE方法:

// Updates an account
accountsFactory.update = function(id) {
    return $http.put('/api/accounts/'+id);
};

// ^ call is to "/api/accounts/acct-1"

然后我的Express API更新路线:

// Dashboard API to update account
app.post('/api/accounts/:id', accountsController.update);

最后我在服务器上accounts-controller.j

module.exports = {
    create: function(req, res) {
        console.log(req.body);
    },

    update: function(req, res) {
        console.log(req.body);
    }
};

有关为什么我会收到404的任何想法? PUT http://localhost:9999/api/accounts/acct-2 404 (Not Found)

1 个答案:

答案 0 :(得分:2)

您有app.post('/api/accounts/:id', accountsController.update);

应为app.put