首页 > 解决方案 > 设置状态后无法发送响应

问题描述

我在我的快递中做了一条路线,在提交时处理表格。
当表单流程遇到错误或问题时,我正在尝试设置状态并向客户端发送响应。
我在前端使用FormData() ,在后端使用强大
这是我试图处理方法回调中的错误的方法:

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

问题是:
1_如果我设置了大多数状态代码(几乎所有状态代码,除了 200 之外),然后我得到一个响应说请求失败,状态代码为 500(或我设置的其他代码)并且 .send() 方法发送的数据是客户端未收到

2_ .send() 带或不带 .end() 不会停止其余代码的执行,因为如果遇到错误,我会尝试在回调中结束响应,否则最后会发送 200 个状态码,代码执行到结束并到达结束,它尝试再次设置状态,当它们被发送到客户端时我得到错误无法设置标题

我试图用不同的方法设置状态码或以其他方式发送响应。
我在网上搜索,我发现正确的方法是 res.status().send() 并且我做得正确,但是我遇到了问题。

这是我的代码(如果需要,我可以粘贴完整代码):

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 !");
}

客户端代码的“获取响应”部分:

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

我希望当我设置状态时,我也能够发送响应。(因为我搜索 res.status().send() 应该是正确的)。
我会很感激你的帮助。

标签: javascriptnode.jsexpresshttpformidable

解决方案


您最好的解决方案是使用 try 和 catch 块然后抛出新错误并创建错误中间件,然后您可以设置状态代码并使用错误调用 next

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


推荐阅读