我正在尝试将附件发送到 API 端点 UploadFxPLink,但我不断收到以下错误:
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'
}
我理解此错误通常意味着在发送响应后设置标头(如状态代码或内容类型),但我检查了我的代码并确保为每个路径返回响应。
相关代码如下:
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('/');
}
});
尝试更换
if (error) {
console.log("Failed to UploadFxP " + error);
return res.send({ "failed": "failed" }); // added return here
}
return res.send({ "success": "success" }); // added return here
与
if (error) {
console.log("Failed to UploadFxP " + error);
res.send({ "failed": "failed" }); // added return here
}
else {res.send({ "success": "success" }); // added return here}