我几天来一直在反对这一点,我仍然不确定是什么问题。一加载localhost,我就会收到无限的项目列表。这些物品通常是空的,不含任何物品。当我尝试删除它们时,我收到404错误,上面写着“api / todos / undefined”。
以下是代码。对不起,我很抱歉。我根本不知道错误在哪里。也许这是在命名?肯定存在路由问题。
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/');
var Todo = mongoose.model('todos', {
text : String
});
module.exports.Todo = Todo;
控制器
var baselTodo = angular.module('baselTodo',[]);
function mainController($scope, $http) {
$scope.formData = {text: ''};
// when landing on the page, get all todos and show them
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
$http.get('/api/todos').success(function(data) {
$scope.todos = data;
})
};
// delete a todo after checking it
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
{
$scope.updateTodo = function(id) {
$scope.newItem = prompt("Please enter your new item: ", "");
$http.put('/api/todos/' + id, {text: $scope.newItem}).success(function(data) {
$scope.todos = data;
});
$http.get('/api/todos').success(function(data) {
$scope.todos = data;
});
}};
};
HTML
<body ng-controller="mainController">
<div class="container">
<div id="person-form">
<form>
<div class="form-group">
<h1>Enter Item:</h1>
<input type="text" ng-model="formData.text">
</div>
<button ng-click="createTodo()">Create</button>
<h3>Current List:</h3>
<ul ng-repeat="todo in todos">
<li> {{todo.text + " || ID: " + todo._id}} </li>
<button ng-click="updateTodo(todo._id)">Update</button>
<button ng-click="deleteTodo(todo._id)">Delete</button>
</ul>
</form>
</div>
</div>
</body>
</html>
服务器
// ================== SERVER.JS ========================
// set up ------------------------------------------
var api = require('./routes/api');
var express = require('express');
var app = express();
// configuration -----------------------------------
app.configure(function() {
app.use(express.static(__dirname + '/public'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
});
// listen (start app with node server.js) ----------
app.listen(3000);
console.log("App listening on port 3000");
// routing -----------------------------------------
// Main Page
app.get('/', function(req, res) {
res.sendfile('./public/index.html');
});
// API Routing
app.get('/api/users', api.read);
app.post('/api/users', api.create);
app.put('/api/users/:_id', api.update);
app.delete('/api/users/:_id', api.delete);
答案 0 :(得分:0)
您的server.js文件中缺少分号。你想要这个:
app.put('/api/todos/:_id', api.update);
也可以在另一个分号上添加分号。