node.js - 为什么当我将 React 表单设置为 multipart/form-data 时,它会被视为 application/json?我上传的文件被视为未定义
问题描述
我正在尝试将带有 React 的图像文件上传到我的 NodeJS 后端,但该文件似乎没有作为 multipart/form-data 进行处理。我已将表单设置为“multipart/form-data”,但每次将其发送到后端时,它都会被读取为“application/json”。
用表单反应组件:
import axios from 'axios';
import React, { useContext, useState, useRef} from 'react';
import CollectionAPI from "../apis/collectionAPI";
import {CollectionContext} from '../context/collectionContext';
const AdminCreateC = (props) => {
const{createItem, setCreateItem} = useContext(CollectionContext);
const [images, setImages] = useState(null);
//insures that the .env file is only run in a development environment and not a production environment
if(process.env.NODE_ENV !== 'production'){
//requires the the .env file configuration be run first hiding all info hidden via the .env file
require('dotenv').config();
}
const handleSubmit = async (e) => {
e.preventDefault()
try{
let formData = new FormData();
formData.append('images', images);
console.log(formData)
axios.post("https://httpbin.org/anything", formData).then(res => console.log(res));
const response = await CollectionAPI.post("/admin/create", {
images: formData,
})
setCreateItem(response.data.data.newItem);
}catch(err){
console.log(err);
}
}
return(
<div>
{/* The form enctype is set to multipart/form-data*/}
<form action="/admin/create" method="POST" encType="multipart/form-data">
<div className="admin-form">
<label className="">Images</label>
<input type="file" onChange={e => setImages(e.target.files[0])} name="images" className="form-control" required/>
</div>
</form>
</div>
)
}
export default AdminCreateC;
NodeJS Route:(req.file 似乎总是未定义)
//Create a collection item
router.post('/admin/create', upload.single('images'), async(req, res) => {
try{
const file = req.file;
console.log("File: " + file);
}catch(err){
console.log(err);
}
})
解决方案
Axiospost
方法的默认Content-Type
值为'application/x-www-form-urlencoded'
.
您需要将其更改为multipart/form-data
axios.post(
"https://httpbin.org/anything",
formData,
{
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(res => console.log(res)
);
推荐阅读
- html - 为什么我在第一个空格上使用空白预换行和 word-space 来设置空格的宽度
- java - 如何将数字转换为字符串,其内容取决于数字的因素。?
- templates - 如何在嵌套的 golang 模板中使用自定义函数?
- apache - 更改权限后,您无权访问此服务器上的 /
- bash - 如何使用 shell 脚本在重新启动时在 localhost 服务器上启动程序
- groovy - 詹金斯找不到定义的功能?
- android - 如何修复“调试”到“发布”开关处的 ExampleInstrumentedTest 错误?
- microsoft-graph-api - 使用 azure 函数处理来自 azure logic app 的会议请求
- c# - 用于 C# 的 Selenium 中的警报阻止执行
- c++ - 为什么编译后会出现错误(c++ eigen)“error C2659: '=' : function as left operand”?