gpt4 book ai didi

node.js - react Node 通过 axios 传递文件,出现 multer 错误 500

转载 作者:行者123 更新时间:2023-12-03 12:13:02 26 4
gpt4 key购买 nike

我正在尝试制作简单的表单来将文件和其他一些数据传递到我的服务器。稍后我将尝试添加数据库查询,但现在我没有看到任何数据传输到那里,所以我被卡住了。
我使用 react 创建了前端:

const [mainPicture, setMainPicture] = useState(null);
const [pictures, setPictures] = useState([]);
const [name, setName] = useState('Name');
const config = {
headers: {
'content-type': 'multipart/form-data'
}
};

function handleSubmit(e) {
e.preventDefault();

const formData = new FormData();
formData.append('name', name);
formData.append('mainPicture', mainPicture);

console.log(formData);

axios
.post(
prefix + '/api/add_project',
formData, {
headers: config.headers,
onUploadProgress: progressEvent => {
console.log('Upload Progress: ' + Math.round(progressEvent.loaded / progressEvent.total * 100) + '%');
}
})
.then((response) => {
alert(response);
})
.catch((error) => {
console.log(error);
});
}

const onDrop = (picture) => {
setPictures([...pictures, picture]);
};

return (
<div>
<form encType="multipart/form-data" onSubmit={handleSubmit}>
<label>
Name:
<input value={name} onChange={(e)=> setName(e.target.value)}
type="text"/>
</label>
<label>
Project Description:
<input onChange={(e)=> setDescription(e.target.value)}
value={description}
type="text"
/>
</label>
<label>
Project Address:
<input onChange={(e)=> setAddress(e.target.value)}
value={address}
type="text"
/>
</label>
<label>
Used Products:
<input onChange={(e)=> setUsed(e.target.value)}
value={used}
type="text"
/>
</label>
<label>
About Products:
<input onChange={(e)=> setAbout(e.target.value)}
value={about}
type="text"
/>
</label>
<input type="file" name="mainPicture" onChange={e=> setMainPicture(e.target.files[0])} />
<button type="submit">Upload</button>
</form>
</div>
);
}
然后我在我的路由中使用 node express 创建了后端函数
从前端接受 api 调用,遵循教程,但我无法在这里找出问题。
var multer = require('multer')
const DIR = './public/images/projects';

const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
const fileName = file.originalname.toLowerCase().split(' ').join('-');
cb(null, fileName)
}
});

const upload = multer({ storage });

//ADD NEW PROJECT
router.post('/api/add_project', upload.single('mainPicture'), (req, res, next) => {
console.log("Body ---", req.body);
console.log('Files--', req.file);
console.log('file name: ', req.file.name);
});
在我的 pm2 monit 中,我得到了这个:
enter image description here
问题是什么?

最佳答案

似乎有一个 issue带标题content-type ,他们说不应传递 header ,因此 axios 可以使用适当的边界设置它。
希望这可以帮助。

关于node.js - react Node 通过 axios 传递文件,出现 multer 错误 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62655275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com