Prisma+Express文件上传表单客户端集成报错:Cannot read properties of undefined (reading 'img')
问题
我正在尝试创建一个包含文件上传功能的输入表单,后端采用Prisma和Express框架。使用Postman测试时数据提交成功,但与客户端集成时出现报错:Cannot read properties of undefined (reading 'img')。
后端代码
const test = async (req = request, res = response) => { try { const { nama } = req.body; //handle file upload const file = await req.files.img; const fileSize = file.data.length; const ext = path.extname(file.name); const fileName = file.md5 + ext; const url = `${req.protocol}://${req.get("host")}/testing/${fileName}`; const allowType = [".png", ".jpg", ".jpeg"]; if (!allowType.includes(ext.toLowerCase())) return res.status(422).json({ message: "Harus bertype JPG,JPEG,PNG", }); if (fileSize > 5000000) return res.status(422).json({ message: "File terlalu besar, max 5 MB", }); file.mv(`./public/testing/${fileName}`, async (err) => { if (err) return res.status(500).json({ message: err.message }); const testpost = await Test.create({ data: { nama: nama, img: fileName, url: url, }, }); res.status(201).json({ status: "succes", query: testpost, }); }); } catch (error) { res.status(500).json({ succes: false, error: error.message, }); } };
客户端代码
const submit = (data) => { let formdata = new FormData(); formdata.append("nama", data.nama); formdata.append("img", data.img[0]); let object = {}; formdata.forEach(function (value, key) { object[key] = value; }); axios .post(`http://localhost:5000/testing`, { headers: { "Content-Type": "multipart/form-data", }, body: object, }) .then((res) => { console.log(res); }) .catch((err) => { console.error(err); }); };
解决方案
客户端代码存在两个核心问题,导致后端无法获取到上传的文件:
- 错误地将FormData转为普通对象:文件是二进制数据,无法通过普通JSON对象传递,必须直接使用FormData实例作为请求体。
- Axios请求参数格式错误:Axios的
post方法第二个参数是请求数据,请求头需要放在第三个参数的配置对象中;同时不需要手动设置Content-Type为multipart/form-data——Axios会自动根据FormData生成包含boundary的正确请求头。
修复后的客户端代码:
const submit = (data) => { const formdata = new FormData(); formdata.append("nama", data.nama); formdata.append("img", data.img[0]); axios .post(`http://localhost:5000/testing`, formdata, { // 无需手动设置Content-Type,Axios会自动处理 }) .then((res) => { console.log(res); }) .catch((err) => { console.error(err); }); };
内容的提问来源于stack exchange,提问作者Ms. Hidayatullah
相关产品推荐
相关产品推荐

