Search code examples
javascriptamazon-web-servicesamazon-ec2production

Cannot set headers after they are sent to the client in production


Im running out of idea,how im going to solve this problem

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

when I run my node js code in ec2 instance(production) but works perfectly in my localhost.

What Im actually doing is uploading img to s3 bucket using node js API https://grokonez.com/aws/node-js-restapis-upload-file-to-amazon-s3-using-express-multer-aws-sdk

var stream = require('stream');

 const s3 = require('../config/s3.config.js');

 exports.doUpload = (req, res) => {
const s3Client = s3.s3Client;
const params = s3.uploadParams;

params.Key = Date.now() +'_'+req.file.originalname
params.Body = req.file.buffer;

s3Client.upload(params, (err, data) => {
    if (err) {
        res.status(500).json({error:"Error -> " + err});
    }
    res.json({message: 'File uploaded successfully! -> keyname = ' + params.Key,file_name: params.Key});

});
}

this is my code in controller


Solution

  • Here you got an error InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records and in err block you set res.status so first this block is executed and a response is sent to the client, after this when it tries to execute `res.json' this error occurs, all you need is use another condition for data.

    s3Client.upload(params, (err, data) => {
        if (err) {
            res.status(500).json({error:"Error -> " + err});
        } else if(data){
            res.json({message: 'File uploaded successfully! -> keyname = ' + params.Key,file_name: params.Key});
        }
    });
    

    with this code, you can handle your error without getting any ERR_HTTP_HEADERS_SENT error.