本文介绍了如何修复 Javascript 中的“TypeError:无法读取未定义的属性‘title’"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 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: 无法读取未定义的属性title"C:\Personal\html-css\11-Intro_to_Node_Mongo_and_REST_APIs\swag-shop-api\server.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());

这篇关于如何修复 Javascript 中的“TypeError:无法读取未定义的属性‘title’"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 04:56