1

I need to send a picture using axios, then output its url to the console. The backend works fine, it gives an array and the picture is loaded into the folder. But for some reason I cannot output to the front through then to the console. Doesn't output anything at all, although the backend returns that the picture was successfully loaded

const uploadImage = file => {
    return new Promise((resolve, reject) => {
        let formData = new FormData()
        formData.append('imagesUp', file)

        const config = {
            headers: {
                'Content-Type': 'multipart/form-data',
                Folder: 'editor',
            },
        }

        axios.post('/api/upload', formData, config).then(responseImage => {
            console.log(responseImage)
            resolve({ data: { link: '//werafgrswe' } })
        })
    })
}
{
  "status": "success",
  "message": "File uploaded successfully",
  "data": [
    {
      "_id": 0,
      "name": "2020result-global-town-1609439624185.jpg",
      "path": "/uploads/editor/2020result-global-town-1609439624185.jpg",
      "size": "1.13 MB"
    }
  ]
}```
DjusTV
  • 47
  • 6
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! And add some error handling. – Bergi Dec 31 '20 at 18:54
  • 1
    Are you saying the `console.log(responseImage)` doesn't happen? And the JSON data you posted is the response you're getting from your server, not the log? – Bergi Dec 31 '20 at 18:56
  • @Bergi Yes, its response from server – DjusTV Jan 01 '21 at 07:36

1 Answers1

0

Remove additional Promise

const uploadImage = (file) => {
  let formData = new FormData();
  formData.append("imagesUp", file);

  const config = {
    headers: {
      "Content-Type": "multipart/form-data",
      Folder: "editor"
    }
  };

  return axios.post("/api/upload", formData, config).then((responseImage) => {
    return responseImage.data;
  });
};
React.useEffect(() => {
  uploadImage(file).then((data) => {
    console.log(data);
  });
}, [file]);
Lashan Fernando
  • 1,187
  • 1
  • 7
  • 21