Reputation: 1
I am trying to send an attachment to an API endpoint UploadFxPLink, but I keep getting the following error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:399:5)
at ServerResponse.setHeader (node:_http_outgoing:645:11)
at ServerResponse.header (D:\NIDC\BL1\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (D:\NIDC\BL1\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (D:\NIDC\BL1\node_modules\express\lib\response.js:267:15)
at ServerResponse.send (D:\NIDC\BL1\node_modules\express\lib\response.js:158:21)
at Request._callback (D:\NIDC\BL1\ors.js:2848:11)
at self.callback (D:\NIDC\BL1\node_modules\request\request.js:185:22)
at Request.emit (node:events:513:28)
at Request.onRequestError (D:\NIDC\BL1\node_modules\request\request.js:877:8) {
code: 'ERR_HTTP_HEADERS_SENT'
}
I understand this error usually means that headers (like status code or content-type) are being set after the response has already been sent, but I’ve checked my code and made sure I’m returning a response for every path.
Here’s the relevant code:
app.post('/UploadFxP', function (req, res) {
var trackngNo = req.session.TrackingNo;
var attachmentId = req.body.attachmentId;
var trackNo = req.body.trackNo;
var userId = req.session.userID;
var token = req.session.token;
var atachment = req.body.atachment;
var attachment = atachment.replace("data:application/pdf;base64,", "");
console.log('trackingNo: ', trackngNo)
if (req.session.userID) {
request({
url: UploadFxPLink,
method: 'POST',
json: {
trackNo: trackNo,
trackngNo: trackngNo,
userId: userId,
attachmentId: attachmentId,
atachment: attachment,
token: token
},
headers: {
'Authorization': `Bearer ${token}`
}
}, function (error, response, body) {
if (error) {
console.log("Failed to UploadFxP " + error);
return res.send({ "failed": "failed" }); // added return here
}
return res.send({ "success": "success" }); // added return here
});
} else {
res.redirect('/');
}
});
Upvotes: 0
Views: 22
Reputation: 7
Try to replace
if (error) {
console.log("Failed to UploadFxP " + error);
return res.send({ "failed": "failed" }); // added return here
}
return res.send({ "success": "success" }); // added return here
with
if (error) {
console.log("Failed to UploadFxP " + error);
res.send({ "failed": "failed" }); // added return here
}
else {res.send({ "success": "success" }); // added return here}
If it not helped you try to replace
headers: {
'Authorization': `Bearer ${token}`
}
with
res.set('Authorization', `Bearer ${token}`);
If and this not helped you - share more code
Upvotes: 0