'Uploading Image With Reactjs and Mongo

I want to create a simple app to upload an image with its Profile to mongoDB Using React and Express.I followed many tutorials but it was useless . I always run into "TypeError: Cannot read properties of undefined (reading 'file')" Here is the React Js Code (I don't want to use <//Form>):

    function App() {

  const [file, setFile] = useState('');

  onchange=(e)=>{
    setFile(e.target.files[0])
  }

  onsubmit=(e)=>{
    e.preventDefault()
    const data = new FormData()
    data.append('file',file)
    axios.post('http://localhost:8000/addbook',data)
    .then((res)=>{
        console.log('Saved Successfully')
    })
    .catch((err)=>{
    console.log('Error')
    })
  }

  return (
    <div className="App">
        <input type='file'name="file"  onChange={onchange} />
        <input  type='submit' onClick={onsubmit}/>
      
    </div>
  );
}

export default App;

This is the Book Schema(Mongoose)

const BookSchema = new Schema({
    bookname:{
        type:String
    },
    bookimage:{
       type: String
    },
    authorname:{
        type:String
    },
    isbn:{
        type:String
    },
    category:{
        type:String
    },
    language:{
        type:String
    },
    rating:{
        type:Number
    },
    numberofrating:{
        type:Number
    }

This is the Backend (Router)

const express= require('express')
const { append } = require('express/lib/response')
const UserRouter=express.Router()
const Book = require('../Schemas/BookSchema')

UserRouter.use(express.json())
const multer=require('multer')



UserRouter.use(express.static(__dirname+'./public/'))

var Storage= multer.diskStorage({
    destination:"./public/uploads/",
    filename: (req, file, cb)=>{
       cb(null, file.fieldname+" "+Date.now()+path.extname(file.originalname))
    }
  }
);

var upload = multer({
    storage:Storage
  }).single('file');

UserRouter.post('/addbook',upload,(req,res)=>{
   const newbook = new Book({
    "bookname":'MyBook',
    "bookimage":req.files.file,
    "authorname":'Mansour',
    "isbn":11122,
    "category":'English',
    "language":'English',
    "rating":0,
    "numberofrating":0
   })
   newbook.save()
   .then((res)=>{
       console.log('Saved Successfully')
   })
   .catch((err)=>{
    console.log('Error')
   })
    
})


module.exports=UserRouter

I am an absolute Beginner so it might be an easy Thing I wonder also , why Create a Folder Called Uploads . I want to store the image in mongodb and later be able to retrieve it along with the book data to display.Note: When i print (req.files) it is undefined



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source