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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…