5

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)

CJ Cruz
  • 98
  • 1
  • 2
  • 7
  • What does the error say if you log it on the server? `console.error(err)` – Cory Danielson Sep 16 '19 at 18:58
  • in you `catch` code please write `console.log(err)` and paste what the error said here. – MBehtemam Sep 16 '19 at 19:46
  • No error if i do console.log(err). because the server side is rendering correctly. – CJ Cruz Sep 17 '19 at 16:12
  • Are you using https://www.npmjs.com/package/multer ? Is that how `image` is being converted to `req.file`? – Cory Danielson Sep 19 '19 at 00:56
  • You mentioned that the files are being uploaded correctly, so your error might be in how you are sending the response. `res.send(result);` might be causing the problem. Does the request return a 500 in the your browser dev tools? What actually is `result`? – Cory Danielson Sep 19 '19 at 01:06
  • Also just a heads up, be careful not to share any private keys or tokens and whatnot when you respond to these comments. I'm looking at the cloudinary docs and see that there are some things of that nature. https://cloudinary.com/documentation/image_upload_api_reference – Cory Danielson Sep 19 '19 at 01:09
  • @Cory Danielson It doesnt return the result because of status 500. I'm still trying to figure out what causes it to stop sending the data. Thanks for the heads up tho. – CJ Cruz Sep 19 '19 at 17:29
  • @Cory Danielson Yes it is how the image is converted. I'm fetching req.file in cloudinary. – CJ Cruz Sep 19 '19 at 17:30
  • What does the failed request look like in the browser dev tools? There might be something there that gives some kind of clue about why/where it's failing. – Cory Danielson Sep 19 '19 at 20:00

1 Answers1

3

first I can't see any headers like this :

const config = {
            headers: { 'content-type': 'multipart/form-data' }
           }

so it should be like this :

   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));

also I can't see you server code but please check that you have multer in you package and also you express config.

MBehtemam
  • 7,865
  • 15
  • 66
  • 108
  • @CJCruz could you please update your question with server codes ? thanks. – MBehtemam Sep 15 '19 at 11:33
  • the question is updated. the server side is working well and it's uploading the files in cloudinary storage. I still can't figure out why the client doesn't work. I also updated the required dependencies above. Thanks. – CJ Cruz Sep 16 '19 at 18:28
  • I was going to say that your server isn't working because you're getting a 500 error, which means a server error... but then I noticed you're using this: `catch(err) { res.status(500).send('Server Error'); }` So what you're really doing is masking your error with a fake 500 internal server error when you should be writing out what the real error is that you're getting back. Once you know what the real error is, you should have a better clue/understanding on how to proceed. – TechGnome Sep 16 '19 at 18:35
  • Tried putting console.log(err). But the server code is uploading correctly and doesn't have an error. – CJ Cruz Sep 17 '19 at 16:15