Request.headers missing or undefined - node.js

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

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

IP reported as null in Node.jsExpress...how is that possible?

I have a website with a Node.js/Express backend and I need to log the visitor's IP address. It seems this should be a fairly straightforward process, however I am having continuous difficulty with it. My code is similar:
const express = require('express');
const app = express();
var port = 443;
app.get('/', function (req, res) {
var site = req.hostname; //example returns "localhost" from "localhost:8080"
var splits = site.split("."); //"split" on "periods"
var subdomain = String(splits[1])
var _host = req.headers.host;
var _userIP = req.headers['x-forwarded-for'] || req.socket.remoteAddress || null;
console.log('_userIP is: ', _userIP); //returns 'null'
//...
});
//...
// Start server...
var webServer = app.listen(process.env.PORT || port, function(request, response) { console.log(" Received request for " + new Date()); } );
console.log('Listening on port ' + port);
//...
console.log("***CREATING WEBSOCKET SERVER");
var wsServer = new WebSocketServer({
httpServer: webServer,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
For guidance I am using the following source for information: "https://stackoverflow.com/questions/8107856/how-to-determine-a-users-ip-address-in-node".
My console.log statement returns "null" as the value for the '_userIP' variable...why??? As I understand ANY connection made to the server should have some sort of IP address, correct? If that is the case then the 'null' as my 'fallback' variable definition should never be assigned, however it is...
Any advice is greatly appreciated.
BTW I have also attempted assigning the '_userIP' variable to "req.ip" as:
console.log('_userIP is: ', req.ip);
...without success. I believe it returned 'undefined' if I remember correctly.
I have also tried:
_userIP = req.header('x-forwarded-for') ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
This code throws an error, I believe because the 'req.connection.socket.remoteAddress' is deprecated...?
If it makes a difference I believe this code displays "::1" if it is run on localhost...which indicates it is functional. Why would the code fail to display a user IP address when executed on a 'real' server? Is it possible my server software (Plesk) may be somehow blocking the IP address?

Error occurred while trying to proxy request [...] from 192.168.0.4:3000 to http://192.168.0.4:5000 (ECONNRESET)

I'm working on my first project using react and node and have been stuck on this problem for a while. I keep getting this error when trying to connect to my site using the ip address, but if I just do localhost:3000 it works perfectly. I want to be able to connect via the IP address so I can test it across devices. Here is the full error:
[HPM] Error occurred while trying to proxy request /socket.io/?EIO=3&transport=polling&t=N4EqtUl&sid=kz_I098ZM2h1Z6WZAAAI from 192.168.0.4:3000 to http://192.168.0.4:5000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
I checkout out this post and implemented setupProxy.js like the second answer suggested, but it still isn't working.
Here is my node server (index.js):
const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const path = require('path')
const port = process.env.PORT || 5000;
app.use(express.static(path.join(__dirname, 'client/build')));
io.on('connection', function(socket) {
console.log('a user connected');
});
// Anything that doesn't match the above, send back index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'))
})
http.listen(port || 5000, function () {
console.log('listening on', port);
});

appmetrics(https://github.com/RuntimeTools/appmetrics/issues) request and http event not working

Hi Please see below sample code.
const express = require('express')
const app = express()
var port = process.env.PORT || 3000;
var appmetrics = require('appmetrics');
var monitor = appmetrics.monitor();
appmetrics.enable('http');
appmetrics.enable('request');
monitor.on('request', function (request) {
console.log('request', request);
});
monitor.on('http', function (http) {
console.log('http', http);
});
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(port, function () {
console.log('Example app listening on port 3000!')
})
'
Whenever I fire localhost:3000 from browser. I get 'Hello World!' reply but logs doesn't show any request or http event. Can somebody help me to point out issue.
I am using latest appmetrics version.
Thanks in Advance.
Have you tried putting line 4 (the appmetrics require line) at the top of the code? If it works, please close the issue you raised https://github.com/RuntimeTools/appmetrics/issues/452

is this the correct way to send data received from twitter api to the browser using nodejs?

I am still learning nodejs and was listening to daniel shiffman's video on how to setup the twitter api and how to get data from it.
Now, the code was working and I was getting back data, but it was all happening in the terminal.
What I wanted to do was to show the twitter data in my browser and wasnt sure how to do that. I tried searching for it, but didnt get much help.
So, I just tried doing whatever I knew and it worked and therefore I am still not sure that the code I have written is the proper way to do this.
I'd love to know if there's a mistake somewhere or If there's some other way I should have done this.
Anyways, here's the code
var http = require('http');
var express = require('express');
var app = express();
var port = 8080; // Use 8080 for local development because you might already have apache running on 80
console.log('The bot is starting');
var Twit = require('twit');
var config = require('./config');
console.log(config);
var T = new Twit(config);
var params ={
q:'spider',
count:5
}
T.get('search/tweets', params, gotData);
function gotData(err, data, response) {
var tweets = data.statuses;
app.get('/',function(req,res){
req=params;
var tweetz='';
for(var i=0;i<tweets.length;i++){
console.log(tweets[i].text+'================================');
tweetz = '<p>'+ tweetz+tweets[i].text+'</p>';
}
res.send(tweetz);
});
}
app.listen(port, function () {
console.log(`app listening on port ${port}!`);
});
The mistake you are doing is declaring app.get inside the callback.
app.get("/", function....) is a route which responds to GET requests which means whenever a user requests for "/", the callback which is the function(req, res) is called.
So the code should be:
app.get("/", function(req, res) {
// User requested for "/" route, now get tweets
T.get('search/tweets', params, function(err, data) {
//Tweets received, now send the tweets to the user
var tweets = data.statuses;
return res.send(tweets);
})
})
Then go to http://localhost:8080/ and it should work.

Creating web server with express (node.js)

js and am trying to create a web server and server side code for my web application.
I understand express is used to get access to all static files.
I am trying to start a simple server using express as follows:
var express = require("express");
var url = require("url");
var http = require("http");
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/Client"));
http.createServer(app).listen(port, function(req,res){
console.log("Server running at: " + "http://" + port);
res.writeHead(200,{
"Content-Type":"text/plain"
});
});
I cant seem to do anything with my res variable in my callback, which I am trying to use as a response object. Allowing me to do things like:
res.end(¨hello world¨);
Is this callback even allowed, or how can I start sending responses etc. I am on virtual box (linux) machine, and using res always gives error (undefined methods etc.). Thanks in advance,
http.createServer(app).listen(port, [hostname], [backlog], [callback])
There are no parameters given to the callback function. This is why req and res are undefined.
So you may change your code to:
app.listen(port, function(){
console.log("Server running at: " + "http://localhost:" + port);
});
app.get('/', function(req,res) {
res.status(200).send('Hello World!')
})
So take a look at the documentation of app.listen() and app.get()

Resources