I was wondering how to send an image and other data to my node server using axios in react.This is the code I have and I can either send the formData or the data currently. Help on how to get them both to the controller on my server would be appreciated.
client side
const [file,setFile] = useState('')
const [productName,setProduct] = useState('')
const onSubmit = (e)=>{
e.preventDefault();
const fd = new FormData();
fd.append('file',file)
fd.append('product',productName)
axios.post('http://localhost:5000/upload/product',fd,{
headers:{
'Content-Type': 'multipart/form-data'
}
})
server side
const bodyparser = require('body-parser');
const multer = require('multer');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
const productStorage = multer.diskStorage({
destination: './client/public/upload',
filename : (req,file,cb)=>{
cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({
storage : productStorage,
limits:{fileSize:1000000},
}).single("file")
app.post('/upload/product',(req,res)=>{
console.log(req.body.product) // undefined ??? <-- my problem
upload(req,res,err=>{
if(err){
console.log('upload failed')
}else{
console.log('upload success')
}
})
})
i can receive the file but i cant receive the product name string . the console shows undefined.