如何修复'TypeError:无法读取 Javascript 中未定义的属性'标题'
我刚开始使用 Javascript 和 Node.js.我有一个 server.js.
I just get started with Javascript and Node.js. I have a server.js.
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/swag-shop');
var Product = require('./model/product');
app.post('/product', function(request, response) {
var product = new Product();
product.title = request.body.title;
product.price = request.body.price;
product.save(function(err, savedProduct) {
if (err) {
response.status(500).send({
error: "Couldn't save product. Something is wrong!"
});
} else {
response.send(savedProduct);
}
});
});
在此我指的是另一个 javascript.(var Product = require('./model/product');)
In this I refer to an other javascript. (var Product = require('./model/product');)
这里是:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var product = new Schema({
title: String,
price: Number,
likes: {type: Number, default: 0},
});
module.exports = mongoose.model('Product', product);
我想用 Postman 做一个原型,所以我发布了这个 json.
I wanted to make a prototype with Postman, so I posted this json.
{
"title":"ubi",
"price":12.23
}
这是我收到的错误消息.
This is the error message what I got.
TypeError:无法读取未定义的属性标题"C:Personalhtml-css11-Intro_to_Node_Mongo_and_REST_APIsswag-shop-apiserver.js:11:51
TypeError: Cannot read property 'title' of undefined at C:Personalhtml-css11-Intro_to_Node_Mongo_and_REST_APIsswag-shop-apiserver.js:11:51
知道有什么问题吗?
推荐答案
如果你想访问请求的正文,你可以使用 bodyParser 中间件解析请求体
if you are wanting to access the body of the request, you can use the bodyParser middleware to parse the request body
const express = require('express');
const app = express();
app.use(express.bodyParser());
相关文章