如何修复'TypeError:无法读取 Javascript 中未定义的属性'标题'

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)