router.post('/addtodo', (req, res, next) => {
let todo = new Todos({
text: req.body.text,
date: new Date(),
});
Todos.addTodo(todo, (err, todos, next) => {
if(err) throw err;
res.json(todos);
});
});
我正在尝试使用上述方法在Todo架构中保存文档 架构和方法如下
const todoSchema = mongoose.Schema({
text: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
const Todos = module.exports = mongoose.model('todos', todoSchema);
//Retrieve documents
module.exports.getTodos = (callback) => {
Todos.find(callback);
};
//Add document
module.exports.addTodo = (todo, callback) => {
Todos.create(todo, callback);
};
但是当我尝试使用邮递员POST一个json对象时,它显示了这个错误。
<body>
<pre>TypeError: Cannot read property 'text' of undefined
<br> at router.post (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\router\todoroute.js:18:24)
<br> at Layer.handle [as handle_request] (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\layer.js:95:5)
<br> at next (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\route.js:137:13)
<br> at Route.dispatch (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\route.js:112:3)
<br> at Layer.handle [as handle_request] (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\layer.js:95:5)
<br> at C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:281:22
<br> at Function.process_params (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:335:12)
<br> at next (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:275:10)
<br> at Function.handle (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:174:3)
<br> at router (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:47:12)
<br> at Layer.handle [as handle_request] (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\layer.js:95:5)
<br> at trim_prefix (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:317:13)
<br> at C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:284:7
<br> at Function.process_params (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:335:12)
<br> at next (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\router\index.js:275:10)
<br> at expressInit (C:\Users\shahaji.shinde\Desktop\practice\todo-mean\node_modules\express\lib\middleware\init.js:40:5)
</pre>
</body>
错误位于第一个代码段行号3中。
答案 0 :(得分:0)
您发布的信息让我想到了两个可能的原因: - 这可能是因为您没有发送适当的Content-Type:application / json(检查它)。 - 服务器还没准备好解析json: 为此,你应该有这样的东西:
var bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json({limit: '10mb'}));
让我知道它是否有助于你