Search code examples
reactjsfile-uploadaxiosundefinedform-data

Param values are undefined during axios file upload along with text upload using FormData


I'm building a simple books management application. In a particular page, I need to upload a book's details along with a picture of the book.

I'm using formData and axios to do this. In the same request, sending the optional image as well as the text inputs. But on reading the text fields from the body in the server side, all of them are undefined.

How can I resolve this issue ?

addBooksForm.js

import {  useContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import "./addbooksform.css";
import axios from "axios"
import { authContext } from "../../App";

const Addbooks = () => {

    // eslint-disable-next-line
    const [authDet, setAuthDet] = useContext(authContext);
    const navigate = useNavigate()
    const [values, setValues] = useState({
        title: "",
        author: "",
        genreId: 1,
        price: 0,
        picture:null
    });

    const handleSubmit = async (e) => {
        e.preventDefault();
        let data = new FormData()
        data.set("title", values.title)
        data.set("author", values.author)
        data.set("genreId", values.genreId)
        data.set("price", values.price)
        data.set("picture", values.picture)
        console.log(values)

        const response = await axios.post("http://localhost:5000/api/books/",data,
        {
            headers:{
            Authorization:`Token ${authDet.accessToken}`
        }
        })


        if (response.status === 200) {
            navigate('/yourbooks');
        } else {
            console.log("Error occurred "+ response)
        }
    };



    const onChange = (e) => {
        setValues({ ...values, [e.target.name]: e.target.value });
    };


    const onFileChange = (e) => {
        setValues({...values, [e.target.name] : e.target.files[0] })
    }

return (
    <div className="addbooks">
        <form onSubmit={handleSubmit}>
        <h3>Title</h3>
        <input type="text" name="title" required={true} onChange={onChange} value={values.title}/>
        <h3>Author</h3>
        <input type="text" name="author" required={true} onChange={onChange} value={values.author}/>
        <h3>Genre</h3>
        <input type="number" name="genreId" required={true} onChange={onChange} value={values.genreId}/>
        <h3>Price</h3>
        <input type="number" name="price" required={true} onChange={onChange} value={values.price}/>
        <h3>Upload picture</h3>
        <input type="file" name="picture" onChange={onFileChange}/>
        <button>Add</button>
        </form>
    </div>
);

};

export default Addbooks;

I have also tried adding content-type:multipart/form-data in the config

Server side controller:

const addBooks = (e) => {
    const { title, author, price, genreId } = req.body;
    // further processing
}

here, all the fields are undefined

server.js:

app.use(express.urlencoded({extended:true}))
app.use(express.json())
app.use(cors())

Any help is appreciated. thanks in advance !!


Solution

  • Seems like express by itself cannot handle formData. As shown in the server.js file, I did not use any middleware other than express parser for handling formData.

    The Issue is solved on using a middleware like multer ( for handling files and formData )