【发布时间】:2020-01-15 11:48:05
【问题描述】:
我在上传图片时遇到问题。我使用 axios 进行 api 请求,使用 multer & cloudinary 进行文件上传。
更新: 在我的依赖中: "axios": "^0.19.0"
我的 .js 文件中的必需依赖项: 从'axios'导入axios;
图片上传已在我的后端使用 express。但是在反应中它仍然不起作用。我已经检查了所有内容,看起来还不错。 下面是代码:
const [text, setText] = useState('');
const [image, setImage] = useState([]);
const onSubmit = async e => {
e.preventDefault();
let data = new FormData();
console.log(image + ' ' + 'this is image pathname')
data.append('image', image);
axios.post('/api/posts/image', data)
.then(res => {
console.log(res.data + 'this is data after api call');
})
.catch(err => console.log(err));
};
return (
<Fragment>
<form onSubmit={e => onSubmit(e)} className="create-post-form">
<input
type="file"
placeholder="Write something..."
name="image"
value={image}
onChange={e => setImage(e.target.value)}
/>
<br/>
<button className="btn btn-post">Post</button>
</form>
</Fragment>
);
更新服务器端代码:
app.post('/image', upload.single('image'), async (req, res) => {
try {
const result = await cloudinary.v2.uploader.upload(req.file.path);
res.send(result);
} catch(err) {
res.status(500).send('Server Error');
}
});
错误信息:POST http://localhost:3000/api/posts/image500(内部服务器错误)
【问题讨论】:
-
如果你在服务器上登录,这个错误说明了什么?
console.error(err) -
在你
catch代码中请写console.log(err)并在此处粘贴错误所说的内容。 -
如果我执行 console.log(err) 没有错误。因为服务器端渲染正确。
-
您在使用npmjs.com/package/multer 吗?这就是
image转换为req.file的方式吗? -
您提到文件已正确上传,因此您的错误可能在于您发送响应的方式。
res.send(result);可能会导致问题。该请求是否在您的浏览器开发工具中返回 500?result究竟是什么?
标签: javascript axios multer cloudinary