I'm having trouble in uploading image in react. I use axios for the api request and multer & cloudinary for the file upload.
Update: In my dependency: "axios": "^0.19.0"
Required dependencies in my .js file: import axios from 'axios';
The image upload already worked in my backend using express. But in react it still doesn't work. I've already checked everything and it seems fine. Below is the code:
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>
);
UPDATE Server side code:
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');
}
});
Error message: POST http://localhost:3000/api/posts/image 500 (Internal Server Error)