Loki
Loki

Reputation: 1

Node.js program exhibits image upload error

I made this post request that saves a title, description, solution and a photo in the database. Everything is required except for the photo. I am trying to make the image upload work but I am unable to put the path of the photo in postman because if I do something like C:\Users\me\Desktop it will cause an error. Is there a problem with the code or is there any other way I can fix this?

router.post('/problem', catchAsync (async (req, res) => {

const { title, description, solution, photo } = req.body;
let uploadPath;

// // 1) Check if title, description and solution exist
if (!title || !description || !solution) {
  
  res.json({
      status: "FAILED",
      message: "Please provide a title, description and solution!"
  })
  console.log("Success!");
  
}

photo = req.files.photo;
uploadPath = __dirname + '/uploads' + photo.name;

sampleFile.mv(uploadPath, function(err) {
    if (err) {
      return res.status(500).send(err);
    }

    res.send('File uploaded to ' + uploadPath);
});
    
//Save it in the database     
const newProblem = new Problem({
    title,
    description,
    solution,
    photo
});
console.log(newProblem);

newProblem.save().then(result => {

    res.json({
        status: "SUCCESS",
        message: "Success",
        data: result
        })

})
.catch(err => {
    console.log(err);
    res.json({
        status: "FAILED",
        message: "Error",
        data: result,
    })

})

The error I get is this:

Error: Cannot set headers after they are sent to the client

Upvotes: 0

Views: 102

Answers (1)

d0rf47
d0rf47

Reputation: 499

I believe the issue is stemming from this part of the code

    sampleFile.mv(uploadPath, function(err) {
    if (err) {
      return res.status(500).send(err);
    }

    res.send('File uploaded to ' + uploadPath);
});

if the file upload is successful you send a response to the client, however the function still has more operations following it in which you attempt to send more responses to the client. If the following code is required on a successful upload, you should not send a response right away, instead use a boolean flag and check this once everything else is complete, only then should you send the response to the client.

Upvotes: 1

Related Questions