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

Time:12-12

I am getting content from a file and returning it. Like below:

app.use(function(req, res, next) {
    // Put some preprocessing here.
    console.log("URL: == ",req.url)

    if(req.url === '/Hello.js'){
        fs.readFile(path.join(__dirname   '../../../dist/Hello.js'), 'utf-8', function(err, content) {
            if (err) {
                console.log("err == ",err)
                one rror(err);
                return;
            }
            res.setHeader('Content-Type', 'application/javascript');
            res.type('.js');
            res.send(content)
        });
    }

    next();
});

In future I might change the content and send as response.

I tried adding return after res.send(content). Still it giving the below error.

_http_outgoing.js:530
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

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

CodePudding user response:

Simply put the next() call into an else statement to prevent the res.send being called later somewhere else in your code.

app.use(function(req, res, next) {
    // Put some preprocessing here.
    console.log("URL: == ",req.url)

    if(req.url === '/Hello.js'){
        fs.readFile(path.join(__dirname   '../../../dist/Hello.js'), 'utf-8', function(err, content) {
            if (err) {
                console.log("err == ",err)
                one rror(err);
                return;
            }
            res.setHeader('Content-Type', 'application/javascript');
            res.type('.js');
            res.send(content)
        });
    } else {

        // only call next if the above code was not processed
        next();

    }
});
  • Related