javascript - 我在 MongoDB 上的 POST 方法的 NodeJS 上出现 TypeError:无法读取未定义的属性(读取“名称”)

我知道这个问题已经被问过很多次了,但其中大多数是针对框架或其他技术堆栈的,我正在使用带有 Express 的 NodeJS 和 MongoDB 上的数据库,并且我正在使用 Postman 测试我的 API。当我尝试在 POST 上将请求发送到 API 时,返回下一条消息(在应用程序上,邮递员只发送:无法获得响应):

addProductsCart.js:21 _req$body = req.body, name = _req$body.name, description = _req$body.description, image = _req$body.image, price = _req$body.price, productType = _req$body.productType; ^ TypeError: Cannot read properties of undefined (reading 'name')

转到错误发送的文件似乎没有任何问题

import Product from '../models/Products';
import Cart from '../models/Cart';


const addProductCart = async (req, res) => {

    const {name, description, image, price, productType} = req.body;
    

    const estaEnProducts = await Product.findOne({name});
  

    const noEstaVacio = name !== "" && description !== "" && image !== "" && price !== "" && productType !== "";
  

    const estaEnElCarrito = await Cart.findOne({name});
  

    if (!estaEnProducts) {
      res.status(400).json({
        mensaje: "This products is not in our DataBase",
      });
  
    } else if (noEstaVacio && !estaEnElCarrito) {
      const newProductInCart = new Cart({name, description, image, price, productType, amount: 1 });
  
      /* Update the property of inCart */
      await Product.findByIdAndUpdate(
        estaEnProducts?._id,
        { inCart: true, name, description, image, price, productType },
        { new: true }
      )
        .then((product) => {
          newProductInCart.save();
          res.json({
            mensaje: `Product added correctly`,
            product,
          });
        })
        .catch((error) => console.error(error));
  
      /* Validate if product is already in cart */
    } else if (estaEnElCarrito) {
      res.status(400).json({
        mensaje: "Product already in cart",
      });
    }
  };
  
  module.exports = addProductCart;

在我的模型中,我为控制器使用完全相同的名称:

import {Schema, model} from 'mongoose';

const cartSchema = new Schema({
    name: {type: String, required: true, unique: true},
    description: {type: String, required: true},
    image: {type: String, required: true, unique: true},
    price: {type: Number, required: true},
    productType: {type: String, required: false},
    amount: {type: Number, required: true},
});

export default model('Cart',cartSchema);

这是产品型号:

import {Schema, model} from 'mongoose';

const productsSchema = new Schema({
    name: {type: String, required: true, unique: true},
    description: {type: String, required: true},
    image: {type: String, required: true, unique: true},
    inCart: {type: Boolean, default: false},
    price: {type: Number, required: true},
    productType: {type: String, required: false},
});

export default model('Products',productsSchema);

我使用 Import 而不是 require 和 Babel,所以那里没有问题

我无法在那里找到错误,而且我认为我正在对 Postman 进行请愿(使用下一个 JSON,这是之前在 DB 上创建的产品,并在标题上告诉 Postman Content-type 是 application/ json)

{
    "name": "producto-test",
    "description": "descripcion de prueba",
    "image": "https://cdn.betterttv.net/emote/58ae8407ff7b7276f8e594f2/3x",
    "price": 100000,
    "productType": "Camara"
}

如果有人知道我做错了什么,我会非常感激,最后我让所有的错误日志,这可能会有所帮助

TypeError: Cannot read properties of undefined (reading 'name')
    at _callee$ (C:\AltoVoltajeFilms\src\controllers\/addProductsCart.js:7:12)
    at tryCatch (C:\AltoVoltajeFilms\node_modules\regenerator-runtime\runtime.js:63:40)
    at Generator.invoke [as _invoke] (C:\AltoVoltajeFilms\node_modules\regenerator-runtime\runtime.js:294:22)
    at Generator.next (C:\AltoVoltajeFilms\node_modules\regenerator-runtime\runtime.js:119:21)
    at asyncGeneratorStep (C:\AltoVoltajeFilms\src\controllers\addProductsCart.js:9:103)
    at _next (C:\AltoVoltajeFilms\src\controllers\addProductsCart.js:11:194)
    at C:\AltoVoltajeFilms\src\controllers\addProductsCart.js:11:364
    at new Promise (<anonymous>)
    at C:\AltoVoltajeFilms\src\controllers\addProductsCart.js:11:97
    at addProductCart (C:\AltoVoltajeFilms\src\controllers\/addProductsCart.js:5:21)

回答1

req.body 未定义。您是否将 json() 添加到您的 express 应用程序中?如果不添加它

const app = express()
app.use(express.json())

相似文章

java - 连接MongoDB

早上好。我在连接到MongoDB数据库时遇到问题。我在docker-compose.yml文件中为自己配置了一个数据库和mongoexpress。使用CommandLineRunner,我想将示例数据...

最新文章