Node.js NodeJS在发送响应后返回错误

Node.js NodeJS在发送响应后返回错误,node.js,Node.js,发送响应后,我的NodeJS控制器返回错误 exports.myFunc = async (req, res, next) => { try { // here I build a XML file const xml = build(); await axios.post(REQUESTURL, xml, { headers: { 'Content-Type': 'text/xml' } }) .then(

发送响应后,我的NodeJS控制器返回错误

exports.myFunc = async (req, res, next) => {
   try {

   // here I build a XML file
   const xml = build();

   await axios.post(REQUESTURL, xml,
      { headers: {
         'Content-Type': 'text/xml'
      } })
      .then(async (result) => {
         const parser = new xml2js.Parser();
         parser.parseStringPromise(result.data).then(async (report) => {
            const xmlResponse = report.BackgroundReports.BackgroundReportPackage[0];
            if(xmlResponse.ErrorReport !== undefined) 
               return res.json(tazworksResponse.ErrorReport[0].ErrorDescription[0]);

            // Continue the code if the response is not an error message
         })
      })
      .catch(async (error) => {
         // here I have a method to email me the error
         return res.json(-1);
      });

      return res.json(0);
   } catch(err) {
      console.log(err);
   }
}
每当axios请求返回带有错误的XML时,如果:

if(xmlResponse.ErrorReport !== undefined) 
   return res.json(xmlResponse.ErrorReport[0].ErrorDescription[0]);
它返回内容为
xmlResponse.ErrorReport[0].ErrorDescription[0]
的正确响应,但NodeJS在终端中也显示以下错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (/PATH/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/PATH/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/PATH/node_modules/express/lib/response.js:267:15)
    at exports.requestReport (/PATH/controllers/myController.js:131:24)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
我是否以无效的方式返回响应


谢谢

这是因为在您的请求完成之前,您会立即发送带有
return res.json(0)
的响应。因此,在您发送该请求之后,您的嵌入式请求将被发送,并尝试响应已经响应的内容


要正确处理这件事,只有一个反应,你应该考虑压平你的承诺链。我添加了
return res.json(0),因此它在处理承诺后返回。