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.
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);
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.
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');
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.
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
});
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);
};
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