How to fix #39;TypeError: Cannot read property #39;title#39; of undefined#39; in Javascript(如何修复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());
这篇关于如何修复'TypeError:无法读取 Javascript 中未定义的属性'标题'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何修复'TypeError:无法读取 Javascript 中未定义的属性'标题'


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01