波纹管是我的 React 组件的代码,我在其中尝试使用 axios 将 formData 从图像文件发送到我的后端 api(node.js 服务器)。我设法访问了后端路由,但是我得到了一个未定义的 req.body...我不确定我将如何调整 axios 请求的标题或其他一些属性来访问这些数据。
function TestForm2() {
const [file, setFile] = useState("");
function handleFile(e) {
let file = e.target.files[0];
setFile(file)
}
async function handleUpload(e){
e.preventDefault()
let formData = new FormData();
formData.append('image', file);
axios({
url: `${BASE_URL}/posts/api/upload`,
method: 'POST',
data: formData,
headers: {
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
},
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
}
return (
<div>
<h1>Test Form 2</h1>
<form onSubmit={handleUpload}>
<label for="image">Select File</label>
<input type="file"
name="image"
onChange={handleFile}
className="form-input"/>
<button className="btn btn-primary" type="submit">Submit</button>
</form>
</div>
)
}
后端路由:
router.post('/api/upload', async function (req,res,next){
try {
console.log(req.file)
console.log(req.body)
console.log("in the backend")
res.json({msg: "WOO"})
} catch (e) {
return next(e)
}
})
现在只是简单的 console.log,将 req.body 显示为空对象 {},将 req.file 显示为未定义。我怀疑 formData 没有以正确的形式传入。虽然我已经添加了 headers: {'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,}
记录的响应将标头显示为
headers:
Accept: "application/json, text/plain, */*"
__proto__: Object