【问题标题】:How to solve "Cannot read property 'title' of undefined"?如何解决“无法读取未定义的属性'标题'”?
【发布时间】:2020-07-23 01:39:26
【问题描述】:

我正在使用 Postman 来了解 API。我的 server.js 文件的内容在下面的代码中。但是,当我通过 Postman 发送帖子时,错误“无法读取未定义的属性 'title'”一直显示。

var Product = require("./model/product");
var WishList = require("./model/wishlist");

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: "Could not save product" });
    } else {
      response.status(200).send(savedProduct);
    }
  });
});

app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.listen(3000, function () {
  console.log("Swag Shop API runing on port 3000...");
});

product.js 文件包含以下代码。

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 文件,但随后显示错误类型:“无法读取未定义的属性 'title'”。

{
    "title": "Test Title",
    "price": 100.00
}

这些是查看我的文件位置的文件夹:Folders

这个solution 使用npm install express@">=3.0.0 <4.0.0" --save 在我的情况下不起作用。在我的终端中使用它后,同样的错误一直显示。

我该如何解决这个问题?

【问题讨论】:

  • 我会尝试在app.post()成功回调中执行console.log(request),以查看它是否具有所需的属性。
  • 您使用服务器和客户端调试器吗?

标签: javascript node.js mongodb mongoose postman


【解决方案1】:

试试这个并使用express.json()bodyParser.json()

如果你进入文件node_module/express/lib/express.js,你可以在模块依赖下看到body-parser模块已经导入var bodyParser = require('body-parser);

var Product = require("./model/product");
var WishList = require("./model/wishlist");

//app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

 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: "Could not save product" });
  } else {
    response.status(200).send(savedProduct);
 }
 });
});

app.listen(3000, function () {
  console.log("Swag Shop API runing on port 3000...");
 });

【讨论】:

    【解决方案2】:
    1. 通过键入 $npm install --save 来安装 express.js 和 mongoose 快递猫鼬
    2. 在 TOP 上键入以下代码以获取正确的 进口和申报
    var express = require('express');
    var app = express();
    var mongoose = require('mongoose');
    var db = mongoose.connect('mongodb://localhost/swag-shop');
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 2019-04-30
      • 2021-05-10
      • 2022-01-26
      • 2019-11-21
      • 2023-02-16
      • 1970-01-01
      • 2018-12-21
      相关资源
      最近更新 更多