如何修复'TypeError:无法读取 Javascript 中未定义的属性'标题' [英] How to fix 'TypeError: Cannot read property 'title' of undefined' in Javascript

查看:18
本文介绍了如何修复'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 中未定义的属性'标题'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆