I am making a simple express api to upload file.I have used formData api. But shows undefined to my image in console but image name is logged in console .What I have done wrong and how I can fix this issue. I have tried but nothing happen. Thanks in advance.
Here is my frontend code
import React, {useState} from 'react'
import axios from 'axios'
const Login=()=>{
const[image,setImage]=useState();
const [imageName,setImageName]=useState("")
const send=async(e)=>{
e.preventDefault()
const formData=new FormData();
formData.append('file',image);
formData.append('name',imageName)
try {
const res=await axios.post('http://localhost:8000/post',formData)
console.log(res.data)
}
catch(err){
console.log(err)
}
}
const handleImage=(e)=>{
let image=e.target.files[0]
console.log(image)
setImageName(image.name);
setImage(image)
}
return(
<>
<form method ="post" encType="multipart/form-data">
<div className="w-1/2 mx-auto h-full overflow-hidden my-4">
<div className="mx-4 py-8 items-center text-center">
<div className="flex items-center py-2 space-x-2 cursor-pointer">
<h2>Login With Google</h2>
</div>
<div className="flex items-center py-2 space-x-2 cursor-pointer">
<h2>Login With Facebook</h2>
<input type="file" name="file" onChange={handleImage}/>
</div>
</div>
</div>
<input type="submit" onClick={send} value="send "></input>
</form>
</>
)
}
export default Login
backend code
const express=require('express');
const cors=require('cors');
const app =express( );
const fs=require('fs');
const fileUpload=require('express-fileupload');
const bodyParser = require('body-parser');
app.get('/',(req,res)=>{
res.send("working")
})
app.use(bodyParser.json())
app.use(fileUpload())
app.use(cors())
app.use(bodyParser.urlencoded({extended:false}))
const dir='upload';
if (fs.existsSync(dir)) {
console.log(`already exist directory ${dir}`);
}
else{
fs.mkdirSync(dir)
}
app.post('/post',(req,res)=>{
console.log(req.body.name)
console.log(req.body.file)
})
const PORT=process.env.PORT||8000
app.listen(PORT,()=>{
console.log(`server is listening in port number ${PORT}`)
})
kindly console req.files instead of req.body.file you will get the object in server
enjoy coding