Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

node.js - NodeJS returning an error after sending response

My NodeJS controller is returning an error after I send a response.

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

Whenever the axios request returning a XML with an error, fail in the if:

if(xmlResponse.ErrorReport !== undefined) 
   return res.json(xmlResponse.ErrorReport[0].ErrorDescription[0]);

It returns the correct response with the content of xmlResponse.ErrorReport[0].ErrorDescription[0], but NodeJS also shows the following error in the terminal:

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'
}

Am I returning the response in an invalid way?

Thanks

question from:https://stackoverflow.com/questions/65906739/nodejs-returning-an-error-after-sending-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because you are immediately sending a response with return res.json(0) before your request has had time to finish. So after you send that, your embedded request gets sent and also tries to respond to something that has already been responded to.

To handle this stuff correctly and only have one response, you should consider trying to flatten your promise chain.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...