0

Trying to upload a image to azure storage blob But the fetch method doesn't works

It works properly in postman but shows error in fetch

Not problem in heroku deployment

What is the problem in this code

This is the code i have tried :

const uploadImage = async () => {
    try {
      const Data = new FormData();

      Data.append('file', image);

      console.log("form data", Data);

      await fetch('https://fame-azure.herokuapp.com/aa', {
        method: 'POST',
        body: Data
      })
    } catch (err) {
      console.log(err);
    }

code in backend :

app.post('/aa', upload.any(), function (req, res, next) {
  console.log(req.files)
  res.send('ok')
  res.status(200).send('Uploaded: ' + req.files)
})

Error :

enter image description here

Dhinesh
  • 59
  • 9
  • 2
    You cannot response again after response – Heartbit Jan 07 '22 at 15:17
  • 1
    Does this answer your question? [ERR\_HTTP\_HEADERS\_SENT: Cannot set headers after they are sent to the client](https://stackoverflow.com/questions/52122272/err-http-headers-sent-cannot-set-headers-after-they-are-sent-to-the-client) – Heartbit Jan 07 '22 at 15:18
  • 3
    Like @Heartbit mentioned, try commenting out `res.send('ok')` in your backend and retry. – GenericUser Jan 07 '22 at 15:19

2 Answers2

2

This is because in your backend, you are first sending a response with res.send('ok'). After that you are again sending a response with res.status(200).send('Uploaded: ' + req.files), however as the response was already submitted, you cannot update/send it again thus the error. If you simply remove the first line, the error would be gone.

2

This is because you are trying to send response twice.

app.post('/aa', upload.any(), function (req, res, next) {
  console.log(req.files)
  // res.send('ok') <-- remove this
  res.status(200).send('Uploaded: ' + req.files) // <-- use this
  res.json({uploaded: req.files}) // <-- or this, using json() method will set the response headers 200 automatically
})

If u think it looks fine in postman, is because the postman doesnt receive any error response from your server, the error only logged in your server.

Bona Ws
  • 356
  • 1
  • 10