CJ *_*ruz 5 javascript cloudinary multer axios
我在反应上传图像时遇到问题。我使用 axios 进行 api 请求,使用 multer 和 cloudinary 进行文件上传。
更新: 在我的依赖项中: "axios": "^0.19.0"
我的 .js 文件中所需的依赖项: import axios from '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>
);
Run Code Online (Sandbox Code Playgroud)
更新服务器端代码:
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>
);
Run Code Online (Sandbox Code Playgroud)
错误消息:POST http://localhost:3000/api/posts/image 500(内部服务器错误)
首先我看不到任何这样的标题:
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
Run Code Online (Sandbox Code Playgroud)
所以应该是这样的:
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
axios.post('/api/posts/image', data,config)
.then(res => {
console.log(res.data + 'this is data after api call');
})
.catch(err => console.log(err));
Run Code Online (Sandbox Code Playgroud)
我也看不到你的服务器代码,但请检查你的包中是否有multer以及你的表达配置。
| 归档时间: |
|
| 查看次数: |
12423 次 |
| 最近记录: |