User 5842
User 5842

Reputation: 3029

Getting original request URL from Express response

Is there an elegant way of retrieving the original request URL from the Express response object?

Using the request object, I can do something like:

getFullUrl(req) {
    return url.format({
        host: environment.getHost(req),
        pathname: req.originalUrl,
        protocol: req.protocol
    });
}

I was wondering if I could do something similar with the response? Looks like the href property gives me what I need but wanted to get some more thoughts.

Upvotes: 0

Views: 815

Answers (1)

jfriend00
jfriend00

Reputation: 708026

You can access res.req to get the request object from the response object so you can then use the same logic you were already using on the request object.

I can't find anywhere that this is documented, but you can see it in console.log() or in the debugger - it's there. So, tread carefully as there may be no guarantee that this never changes.

Both res.req and req.res appear to be Express-specific additions to the request and response objects. You can see them assigned here in the source in a default early middleware handler Express adds:

/**
 * Initialization middleware, exposing the
 * request and response to each other, as well
 * as defaulting the X-Powered-By header field.
 *
 * @param {Function} app
 * @return {Function}
 * @api private
 */

exports.init = function(app){
  return function expressInit(req, res, next){
    if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express');
    req.res = res;
    res.req = req;
    req.next = next;

    setPrototypeOf(req, app.request)
    setPrototypeOf(res, app.response)

    res.locals = res.locals || Object.create(null);

    next();
  };
};

While they don't appear to be documented, the internals of Express rely on them all over the place. Just looking at the response.js file from the Express repository, there are all sorts of uses of res.req internally in Express. So, if they were to remove it in the future, they'd have to change a lot of their own code to do so. I'd say it seems relatively safe to use.

Upvotes: 2

Related Questions