I have a NodeJS server running on an elastic beanstalk instance. The logs of the elastic beanstalk instance is showing:
TypeError: Cannot read property 'replace' of undefined
at Server.<anonymous> (/var/app/current/server.js:48:36)
at Server.emit (events.js:311:20)
at parserOnIncoming (_http_server.js:784:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
The portion of code that is throwing this error is:
http.createServer(function (req, res) {
if(req.headers.host){
let httpsHost = req.headers.host.replace('8081', '8443');
res.writeHead(301, {"Location": "https://" + httpsHost + req.url});
res.end();
}
}).listen(8081);
The purpose of this code is to force redirect all HTTP requests to HTTPS.
The server is working normally, but this error is getting thrown on a constant basis. I see no adverse effects on the server from this error, but it is making my logs look terrible.
- Why is this error even happening? Why do some
req.headersnot have ahostvariable defined? - Why is my null check not preventing this error?