If I have two node.js servers running, how can I tell which server called the processRequest function?
var http = require('http');
var https = require('https');
function processRequest(req, res) {
res.writeHead(200);
res.end("hello world, I'm on port: " + ???.port + "\n");
}
var server1 = http.createServer(processRequest).listen(80);
var server2 = https.createServer(processRequest).listen(443);
Originally I wanted the port number, but couldn't find the object/variable to give it to me. Based on the below answer it makes more sense to determine encrypted vs non-encrypted since the point is to know which of the http servers the request came in on.
env. PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there. So you pass that to app. listen , or to app. set('port', ...) , and that makes your server able to accept a "what port to listen on" parameter from the environment.
The first one runs only once since it is a synchronous method. The * get route is not setup until after it returns. The second will run when any http request comes to the server. And yes, it will block the whole server for the duration of that synchronous call (I/O cost to open and read the contents of the file).
The req
parameter is an instance of IncomingMessage from which you can access the socket.
From there you can access both the localPort and remotePort.
Something like:
console.log(req.socket.localPort);
console.log(req.socket.remotePort);
This way you get the port number:
var http = require('http');
var server = http.createServer().listen(8080);
server.on('request', function(req, res){
res.writeHead(200, {"Content-Type": "text/html; charset: UTF-8"});
res.write("Hello from Node! ");
res.write(" Server listening on port " + this.address().port);
res.end();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With