【发布时间】:2022-08-13 20:44:02
【问题描述】:
我想在前端制作一个简单的文件上传表单。然后,在后端,我会将有关该文件的信息传递给 API。
这是我在后端调用特定函数并传递数据的前端代码:
import React from \'react\';
import Axios from \'axios\';
const Upload = () => {
// a local state to store the currently selected file.
const [selectedFile, setSelectedFile] = React.useState(null);
const handleSubmit = async (event) => {
event.preventDefault()
//Got all the Infos about my file
console.log(selectedFile)
const formData = new FormData();
formData.append(\"selectedFile\", selectedFile);
//Empty result
console.log(formData)
Axios.get(\"http://localhost:3001/upload\", {
//I will pass the data to a function in the backend
params: {
data: formData,
},
})
.then((Response) => {
console.log(Response)
})
.catch(function (error) {
console.log(error);
});
}
const handleFileSelect = (event) => {
setSelectedFile(event.target.files[0])
}
return (
<form onSubmit={handleSubmit}>
<input type=\"file\" onChange={handleFileSelect}/>
<input type=\"submit\" value=\"Upload File\" />
</form>
)
};
export default Test
在后端,路由调用方法
router.get(\'/upload?\', Upload);
然后最后在后端处理函数
const ApiProcess = (req, res) => {
var axios = require(\'axios\');
var data = req.query
console.log(req.query)
//All the API Stuff
}
但问题是我在后端收到空数据。我的代码有什么问题?
谢谢
编辑
在后端,我使用 multer 并在索引文件顶部添加 \'app.use(multer().any())\' 。这有助于导致我现在无法在后端访问简单的 formData。现在我的函数接收数据日志这个\'[对象:空原型] {}\'
任何想法 ?