Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the base URL for an express router

I have an authentication middleware that needs to make a call to an outside service and provide a callback URL. For example:

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

// This will work just fine
app.use('/', getAuthRouter());

// The redirects here will end up going to /oauth/callback 
//    instead of /admin/oauth/callback
app.use('/admin', getAuthRouter());

function getAuthRouter() {
  var authRouter = express.Router();

  // Setup auth routes
  var callbackUrl = '/oauth/callback';
  var loginUrl    = '/login';

  authRouter.get(callbackUrl, .... });
  authRouter.get(loginUrl, function(req, res, next){
    // Make call to OAuth server
    res.redirect("http://authserver/?callback=" + callbackUrl);
  });

  return authRouter;
}

The problem is that authRouter does not know that it's actually mounted under /admin so it has no way to prepend that to the callback param.

Is there any way that I can get that inside the getAuthRouter function?

like image 450
Fotios Avatar asked Mar 06 '15 00:03

Fotios


2 Answers

Use request.baseUrl, which was designed for this use case.

like image 86
mbavio Avatar answered Nov 15 '22 19:11

mbavio


Use req.url:

You can use req.url.
If you are on http://example.com/test/here it will return /test/here.

Pass it as argument:

But in your case you could also pass the base url as a parameter of your middleware :

function getAuthRouter(baseUrl) {
  var authRouter = express.Router();
  baseUrl = baseUrl || ""; // Default

  // Setup auth routes
  var callbackUrl = baseUrl + '/oauth/callback';
  var loginUrl    = '/login';
  // ...
}

And you'll then call it like so :

app.use('/admin', getAuthRouter("/admin"));

Or

app.use ('/', getAuthRouter()); // Calls default

like image 31
Telokis Avatar answered Nov 15 '22 17:11

Telokis