не может прочитать путь неопределенного объекта - PullRequest
0 голосов
/ 25 января 2020

ПОЖАЛУЙСТА, я использую multer и nodejs для отправки изображения, но всякий раз, когда я нажимаю на кнопку отправки без выбранного файла, я получаю сообщение «невозможно прочитать путь неопределенного», но при выборе файла ошибка не появляется. но я хочу проверить, не выбран ли файл, который express -validator не предоставляет

`app.post("/ashanti",upload.single("pic"),function(req,res){
 const pic=req.file.path;

if(req.file){
console.log(req.file);

}
 const newuser=new user(

     {  pic:pic

      })

    newuser.save().then(function(err,user){
        if(err) throw err

          })
             })

 And this is the multer setup

const storage=multer.diskStorage({
 destination:function(req,file,cb){
      cb(null,"images/ashantiimg");
  },
 filename:function(req,file,cb){
  cb( null , file.fieldname+"-"+Date.now()+file.originalname);
  }


  })
  const filefilter=function(req,file,cb){




   if(file.mimetype==="image/png"||file.mimetype==="image/jpeg"||
 file.mimetype==="image/jpg"){
  cb(null,true)
  }

   else{
      cb(null,false)

   }

   }

const upload=multer({storage:storage,fileFilter:filefilter});

This is the pug file for the form 

 form#frm(method="post" action="/ashanti" enctype="multipart/form-data" )   
 .form-group
  label
   input.form-control.seven(type="file",name="pic") 
   input( type="button" onclick="subi()" value="post") 
   script.
    function subi(){
     const post=document.getElementById("frm");
     post.submit();
     post.reset();
     }`

1 Ответ

0 голосов
/ 25 января 2020

ошибка - именно то, о чем она говорит, если вы пытаетесь прочитать path из undefined

, вы можете думать так:

const testObj = {path: 'my path'}
const path = testObj.path

это будет работать правильно? потому что все определено, но что произойдет, если вы попробуете это:

let testObj; //you only defined the name of the variable, but it is undefined.
let path = testObj.path // can not read path from undefined.

, поэтому в основном вам нужно сделать следующее:

  • убедиться, что переменная определена
  • установить значение по умолчанию для переменной.

убедиться, что оно определено:

app.post("/ashanti",upload.single("pic"),function(req,res){
 // if some of these entries are undefined, we return
 if(!req || !req.file || !req.file.path) return;
 const pic=req.file.path;
 ....
 ....
 ....
}

установить значение по умолчанию:

app.post("/ashanti",upload.single("pic"),function(req,res){
 const { path: pic }= req.file || {}; // we are sure that we are reading from an object.
 if(!pic) return;
 ....
 ....
 ....
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...