简体   繁体   中英

How to fix 'TypeError: Cannot read property 'title' of undefined' in Javascript

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);
    }
  });
});

In this I refer to an other javascript. (var Product = require('./model/product');)

This is here:

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);

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: Cannot read property 'title' of undefined at C:\\Personal\\html-css\\11-Intro_to_Node_Mongo_and_REST_APIs\\swag-shop-api\\server.js:11:51

Any idea what's the problem?

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()); 
app.use(express.json())

把它放在你的app.js中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM