Home > Software design >  Request.headers missing or undefined
Request.headers missing or undefined

Time:10-27

Hopefully somebody will find this a relatively simple answer, but it is beyond me at the moment. I have a Node.js/Express setup. I am simply trying to retrieve the client IP address upon each request to the site. My code is as follows:

const express = require('express');
const app = express();
const port = 3000;

...

// Start server...
var webServer = app.listen(process.env.PORT || port, function(request, response) { 
  console.log(" Received request for "   new Date()); 

  var _FORWARD_IP = request.headers['x-forwarded-for'];
  console.log('_FORWARD_IP (CLIENT IP ADDRESS): '   _FORWARD_IP);       
});

However this throws the following error:

"TypeError: Cannot read property 'headers' of undefined"

Therefore it seems there are no headers in the 'request' object within the 'app.listen' command. I am unsure how to resolve, this is the initial instance of dealing with something like this. If anybody knows an answer or a workaround it is greatly appreciated. I thank you in advance.

Regards

CodePudding user response:

app.listen() just starts the server, telling it to listen for requests. There is no request at that point in your code.

This sounds like a job for some custom middleware

const port = process.env.PORT || 3000;

// Middleware
app.use((req, res, next) => {
  const _FORWARD_IP = req.get('x-forwarded-for');
  console.log('_FORWARD_IP (CLIENT IP ADDRESS):', _FORWARD_IP);
  next();
});

app.listen(port, () => {
  // This callback executes when the server is ready to accept connections
  console.info(`Express server started on port ${port}`);
});
  • Related