I am using Nodejs
with AWS-S3
and sometimes I got the error:
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I have this function to download any file. And when I call it after a certain requests I got the error.
export const downloadFile = async(req: Request, res: Response) => {
res.setHeader('Content-Disposition', 'attachment');
const params = {
Bucket: AWS_S3.Bucket,
Key: req.params.key
};
s3.getObject(params)
.createReadStream()
.on('error', error => {
return res.status(500).json({
message: 'An error ocurred...',
error
});
}).pipe(res);
}
CodePudding user response:
This error happens when you try to send a res after having already sent a res. are your sure your
return res.status(500).json({
message: 'An error ocurred...',
error
});
Is not returning a value after the function has already ended? I would make sure to await the execution of your stream before arriving at the end of the method. Otherwise you will receive in local some OK we are done without actually being done on the server and then attempt to send a result again.