我正在尝试学习平均堆栈,TypeError: Cannot read property '_id' of undefined
现在我在互联网上搜索时遇到了这个错误,人们说我必须包含 body-parser 并且我已经在我的 server.js 文件中,我必须这样做出了点问题,顺便说一句,我确实想提一下,奇怪的是,我的应用程序中没有 node_modules 文件夹,但是在 body-parser 之前,一切正常,我确实将 express 安装为全局包,这是我的文件server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/contactlist', function (req, res) {
db.contactlist.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/contactlist', function (req, res) {
console.log(req.body);
db.contactlist.insert(res.body,function(err,doc){
res.json(doc);
});
});
app.listen(3000);
console.log('Server running on port 3000');
index.html file
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Static Page</title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/angular.min.js"></script>
<script src="/js/controllers/controller.js"></script>
</head>
<body>
<div class="container" ng-controller="AppCtrl">
<h1>Contact List App</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Number</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control" ng-model="contact.name"></td>
<td><input type="text" class="form-control" ng-model="contact.email"></td>
<td><input type="text" class="form-control" ng-model="contact.number"></td>
<td>
<button class="btn btn-primary" ng-click="addContact()">Add</button>
</td>
</tr>
<tr ng-repeat="contact in contactlist">
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.number }}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
controller.js file
var myApp = angular.module('myApp',[]);
myApp.controller('AppCtrl',['$scope','$http',function($scope,$http){
$http.get('/contactlist').success(function(response){
console.log("I got the data");
$scope.contactlist = response;
});
$scope.addContact = function(){
$http.post('/contactlist',$scope.contact).success(function(response){
console.log(response);
});
}
}]);