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?
Use request.baseUrl, which was designed for this use case.
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
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