【问题标题】:error: "Cannot read property 'name' of undefined"错误:“无法读取未定义的属性‘名称’”
【发布时间】:2021-10-04 22:47:47
【问题描述】:

当我使用 router.post(productController.postProduct) 时,代码工作正常(用于获取请求),直到我想通过 mongoDb 中的发布请求保存数据 我收到此错误:无法读取未定义的属性“名称”

导出函数为:

exports.postProduct=async (req,res)=>{
    try{
    
    const newProduct=new Products()
    newProduct.save({
        name: req.body.name,
        price:req.body.price
    })
    

       
        res.status(201).json({
            status:'success',
            data:{
                tour:newProduct
            }
        })}
        catch(err){
            res.status(404).json({
                status:'fail',
                message:err.message

            })
        }
    }

`旅游模型是

const mongoose=require('mongoose');
const slugify=require("slugify")

const productSchema=new mongoose.Schema({

    name:{
        type:String,
        unique:true,
        required:[true,"A Product  must have name"],
        maxLength:[40,"A Product name mus havr less than or equal to 40"],
        minLength:[10,"A Product name must have atleast 10 characherts"],
        
    },
      
    slugify:{
        type:String,
    },
    

    ratingAverage:{

        type:Number,
        default:4.5,
        min:[1,"The rating must begreater than 0"],
        max:[5,"The rating must be less than 5"],
    },
    ratingQuantity:{
        type:Number,
        default:0
    },
    price:{type:Number,
        required:[true,"A Product must have price"]
    },
   
     priceDiscount:{
            type:Number,
            
        },
    summary:{
            type:String,
            trim:true
        },
    description:{
        type:String,
        trim:true
    },
    
    images:[String],
    createdAt:{
        type:Date,
        default:Date.now()
    },
    startDate:[Date],
    

    
    
    

}, 

)

而 app.js 是:

const express=require('express');
const fs=require("fs")
const app=express()
const mongoose=require("mongoose")
const dotenv=require("dotenv")
dotenv.config({path:"./process.env"})
const morgan =require("morgan") 
const productsRoute=require("./Routes/productRoutes")


const DB=process.env.DATABASE.replace(
    "<password>",
    process.env.DATABASE_PASSWORD
)

mongoose.connect(DB,
    {
   
        useNewUrlParser:true,
        useCreateIndex:true,
        useFindAndModify:false,
        useUnifiedTopology: true
    })
    .then(console.log("DB connection successfull"))

app.use(morgan('dev'))

var port=3000
app.listen(port,()=>{
    console.log(`App is running on the port ${port}`);
})

app.use("/api/v1/products",productsRoute)

除了 post 请求之外,所有其他 HTTP 似乎都可以正常工作

【问题讨论】:

  • body-parser 在哪里?
  • 尝试 console.log 你的 req.body.name,看起来它是空的......出于某种原因
  • @NoobDEV-GBL 名称甚至无法设置,因为错误提示 bodyundefined

标签: javascript node.js express


【解决方案1】:

尝试将 app.use(express.urlencoded({extended:false})) 放在 app.js 中所有路由的顶部

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多