1
votes

i have made a route in my express that processes a form when it submits .
i am trying to set a status and send a response to client when the form process faces an error or problem .
i am using FormData() in the front-End and formidable in the back-end .
here is how i am trying to handle errors in the methods call back :

if (err) {
      res.status(500) // i have tried different status-codes !
      .send(`error on parsing : ${err}`)
      .end();      
}

the problem is :
1_ if i set most of status codes ( almost all of them except 200 ) then i get an response says Request failed with status code 500 (or other codes i set) and the data sent by .send() method is not received in the client-side

2_ .send() with or without .end() does not stop rest of code to be executed , as i am trying to end response in call backs if they face error , else at the end a 200 status-code is sent , codes execute till end and reach the end and it tries to again set status and i get error cant set headers when they are sent to the client

i have tried to set status code with different methods or send response in other ways .
i searched the web , and i found out the correct way is res.status().send() and i am doing correctly , however i am facing problem .

here is my code (if you need i can paste full code) :

app.post("/upload", (req, res) => {
  var form = new formidable.IncomingForm();
  form.on("error", err => {
    if (err) {
      res
        .status(500)
        .send(`Error on formidable : ${err}`)
        .end();
        console.log('continued');
    }
  });


  form.encoding = "utf8";
  form.uploadDir = "./uploadedFiles/";
  form.maxFileSize = 2000 * 1024 * 1024;
  form.parse(req, (err, fields, files) => {
    if (err) {

      res.status(500)
      .send(`error on parsing : ${err}`)
      .end();

    }
 // code continues with same style , methods with error handling in call backs  
//at the end of code :  
res.status(200).send("form successfully Submitted !");
}

"getting response" part of Client-side code :

try {
      let response = await axios.post("/upload", FD, {
        "Content-Type": "multipart/form-data"
      });
      console.log(response);

      $("#res")
        .css("display", "block")
        .text(response.data);
      $("#spinnerbox").css("display", "none");
    } catch (error) {
      $("#res")
        .css("display", "block")
        .text(error);
      console.log("Catched Error");
    }

i expect when i set a status i be able to send a response as well . ( as i searched res.status().send() should be correct ) .
i would appreciate your helps .

2

2 Answers

1
votes

your best solution is to use try and catch block then throw new error and create error middleware then you can set the status code and call next with the error

app.get('/route', (req, res, next) => {
  try {
    // do something
    if ('something failed') {
      throw new Error('error message!');
    }
  } catch (err) {
    next(err);
  }
});

// or if you want to set the status code

app.get('/route', (req, res, next) => {
  try {
    // do something
    if ('something failed') {
      res.status(500);
      const error = new Error('error message!');
      next(error);
    }
  } catch (err) {
    next(err);
  }
});
0
votes

You can return a response with .josn too.

200

return res.status(200).json({ msg: 'SUCCESS' });

400

return res.status(400).json({ error: 'ERROR' });

In your instance you got error Error: Can't set headers after they are sent to the client

It's come when your server returns multiple responses of a single request Ex.

// Incorrect Example
if(something) {
  res.status(200).json({ msg: 'SUCCESS' }); 
} 
 res.status(400).json({ error: 'ERROR' });

In the above code, once a condition full-filled then it gives 200 and In other case it will give 400, Si here 2 times response send which occurs such error (Error: Can't set headers after they are sent to the client )

To avoid such error you need to add a keyword return before response.

// Correct Example
if(something) {
 return res.status(200).json({ msg: 'SUCCESS' }); 
} 
return res.status(400).json({ error: 'ERROR' });