我正在尝试学习平均堆栈,但我遇到了这个错误TypeError:无法读取未定义的属性'_id'
现在我通过互联网搜索,人们说我必须包含 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 文件
<!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 文件
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);
});
}
}]);
最佳答案
您应该使用 req.body
而不是 res.body
。
此外,您应该确保向客户端发送正确的Content-Type
。您添加了 JSON 正文解析中间件,但您是发送 JSON POST 请求还是实际上发送 application/x-www-url-encoded
POST 请求(您可以通过放置类似 的内容来检查>console.log(req.headers['content-type'])
在 POST 处理程序中)?
关于javascript - 即使包含主体解析器,也会出现类型错误 : Cannot read property '_id' of undefined,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31101375/