参数值在使用FormData进行文本上传时,axios文件上传期间未定义

huangapple go评论64阅读模式
英文:

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!

英文:

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 &quot;react&quot;;
import { useNavigate } from &quot;react-router-dom&quot;;
import &quot;./addbooksform.css&quot;;
import axios from &quot;axios&quot;
import { authContext } from &quot;../../App&quot;;
const Addbooks = () =&gt; {
// eslint-disable-next-line
const [authDet, setAuthDet] = useContext(authContext);
const navigate = useNavigate()
const [values, setValues] = useState({
title: &quot;&quot;,
author: &quot;&quot;,
genreId: 1,
price: 0,
picture:null
});
const handleSubmit = async (e) =&gt; {
e.preventDefault();
let data = new FormData()
data.set(&quot;title&quot;, values.title)
data.set(&quot;author&quot;, values.author)
data.set(&quot;genreId&quot;, values.genreId)
data.set(&quot;price&quot;, values.price)
data.set(&quot;picture&quot;, values.picture)
console.log(values)
const response = await axios.post(&quot;http://localhost:5000/api/books/&quot;,data,
{
headers:{
Authorization:`Token ${authDet.accessToken}`
}
})
if (response.status === 200) {
navigate(&#39;/yourbooks&#39;);
} else {
console.log(&quot;Error occurred &quot;+ response)
}
};
const onChange = (e) =&gt; {
setValues({ ...values, [e.target.name]: e.target.value });
};
const onFileChange = (e) =&gt; {
setValues({...values, [e.target.name] : e.target.files[0] })
}
return (
&lt;div className=&quot;addbooks&quot;&gt;
&lt;form onSubmit={handleSubmit}&gt;
&lt;h3&gt;Title&lt;/h3&gt;
&lt;input type=&quot;text&quot; name=&quot;title&quot; required={true} onChange={onChange} value={values.title}/&gt;
&lt;h3&gt;Author&lt;/h3&gt;
&lt;input type=&quot;text&quot; name=&quot;author&quot; required={true} onChange={onChange} value={values.author}/&gt;
&lt;h3&gt;Genre&lt;/h3&gt;
&lt;input type=&quot;number&quot; name=&quot;genreId&quot; required={true} onChange={onChange} value={values.genreId}/&gt;
&lt;h3&gt;Price&lt;/h3&gt;
&lt;input type=&quot;number&quot; name=&quot;price&quot; required={true} onChange={onChange} value={values.price}/&gt;
&lt;h3&gt;Upload picture&lt;/h3&gt;
&lt;input type=&quot;file&quot; name=&quot;picture&quot; onChange={onFileChange}/&gt;
&lt;button&gt;Add&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
);

};

export default Addbooks;

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

Server side controller:

const addBooks = (e) =&gt; {
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 !!

答案1

得分: 0

似乎 express 本身无法处理 formData。如 server.js 文件所示,除了使用 express 解析器来处理 formData 外,我没有使用其他中间件。

问题可以通过使用像 multer 这样的中间件来解决(用于处理文件和 formData)。

英文:

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 )

huangapple
  • 本文由 发表于 2023年2月19日 22:59:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定