AngularJS + ExpressJS +猫鼬:添加删除功能

时间:2016-01-20 17:29:44

标签: javascript angularjs node.js express mongoose

我对AngularJS很新,甚至更新ExpressJS和Mongoose。我一直在关注一个教程来发布,并从我的数据库中获取,但我在添加删除功能时遇到了问题。

这是我调用删除功能的地方:

<ul ng-repeat="disease in diseases">
    <li>
        {{ disease.name }}: {{ disease.chipped }}, 
                            {{ disease.received }}, 
                            {{ disease.smashed }}, 
                            {{ disease.complete }}
    </li>
    <button ng-click="removeDisease(disease)"></button>
</ul>

...在我的控制器里我有:

app.controller('MainCtrl', [
    '$scope',
    'TrelloApi',
    'diseases',
    function($scope, TrelloApi, diseases){

        $scope.diseases = diseases.diseases;

        $scope.removeDisease = function(disease) {
            console.log(disease);
            diseases.destroy(disease);
        }
    }
]);

...调用我的diseases工厂:

app.factory('diseases', [
    '$http',
    function($http){

        var o = {
            diseases: []
        };

        o.destroy = function(disease) {
            return $http.delete('/diseases/' + disease._id).success(function(data){
                console.log("Disease " + disease.name + " has been removed!");
                o.getAll();
            });
        };

        return o;
    }
]);

返回404错误: DELETE http://localhost:4000/diseases/<id> 404 (Not Found)即使在我的路线中包括:

var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Disease = mongoose.model('Disease');

// Not functional
router.delete('/diseases/:id', function(req, res, next) {
    console.log(req);
});

// Functional
router.post('/diseases', function(req, res, next) {
  var disease = new Disease(req.body);

  disease.save(function(err, diseases){
    if(err){ return next(err); }

    res.json(diseases);
  });
});

... ui.router包含:

app.config([
    'TrelloApiProvider', 
    '$stateProvider',
    '$urlRouterProvider',
    function(TrelloApiProvider, $stateProvider, $urlRouterProvider) {

        .state('diseases', {
            url: '/diseases/{id}',
            templateUrl: '/javascripts/home/_diseases.html',
            controller: 'MainCtrl'
        });

        $urlRouterProvider.otherwise('home');   
    }
]); 

/javascripts/home/_diseases.html处还有一个模板。我有一种感觉,我错过了一件,但我无法弄清楚它是什么。

1 个答案:

答案 0 :(得分:0)

确保启动Express HTTP服务器:

const express = require('express');
const router = express.Router();

router.delete('/diseases/:id', function(req, res, next) {
  const id = req.params.id;
  console.log(id);
});

const app = express();

app.use('/', router);

const server = http.createServer(app).listen(8080, serverCallback);

function serverCallback() {
  const host = server.address().address;
  const port = server.address().port;
  console.log(`Server listening on ${host}:${port}`);
}