Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access to HTTP server object in node.js express

I am inside a middleware (function(req, res, next) {...}).

Is there a way to access the HTTP server object from the req?

UPDATE

Let me be more specific. I am trying to find out a port that the server listens on, or unix socket path, if it's listening on that.

like image 947
punund Avatar asked Dec 12 '13 16:12

punund


People also ask

How do I get the HTTP server from the Express App?

The usual two ways to start a server for use with Express are this: var express = require('express'); var app = express(); // Express creates a server for you and starts it var server = app. listen(80);

Is Express server HTTP server?

The Express philosophy is to provide small, robust tooling for HTTP servers, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs.

What is HTTP server in node JS?

Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require() method: var http = require('http');


3 Answers

How about in your main app file:

var express = require('express');
var http = require('http');
var app = express();

app.use(app.router);

app.get('/', function (req, res, next) {
  console.log(req.socket.server);
});

app.server = http.createServer(app);
app.server.listen(3000);

As Brad mentioned, Express does expose something resembling the object returned from #createServer(), however, TJ has been giving serious consideration to dropping any inclusion of the HTTP module in express in future releases. Using the code above will be future safe.

like image 86
srquinn Avatar answered Sep 28 '22 09:09

srquinn


If what you are trying to do is expose the server object inside your routers, then yeah, middleware is the way to go:

var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);

app.use(function(req, res, next){ //This must be set before app.router
   req.server = server;
   next();
});

app.use(app.router); 

server.listen(3000);

The middleware is used to expose the server object. Then, you can just access it in any of your routers like so:

app.get('/', function (req, res, next) {
  console.log(req.server.get('port')); // displays 3000
});
like image 39
verybadalloc Avatar answered Sep 28 '22 09:09

verybadalloc


Function app.listen returns your http server.

Source express/lib/application.js

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};
like image 21
pravdomil Avatar answered Sep 28 '22 08:09

pravdomil