7

I am working with node/express/passport/ looking at code that attempts to use a request like: req._parsedUrl.pathname;

I cannot figure out where this variable is coming from. Is this a canonical variable name that is set in a common .js library? It doesn't seem exposed in any headers.

2 Answers 2

20

req._parsedUrl is created by the parseurl library which is used by Express' Router when handling an incoming request.

The Router doesn't actually intend to create req._parsedUrl. Instead parseurl creates the variable as a form of optimization through caching.

If you want to use req._parsedUrl.pathname do the following instead in order to ensure that your server doesn't crash if req._parsedUrl is missing:

var parseUrl = require('parseurl');

function yourMiddleware(req, res, next) {
    var pathname = parseUrl(req).pathname;
    // Do your thing with pathname
}

parseurl will return req._parsedUrl if it already exists or if not it does the parsing for the first time. Now you get the pathname in a save way while still not parsing the url more than once.

Sign up to request clarification or add additional context in comments.

Comments

-2

You can write a middleware to handle then set properties for req.

var myMiddleWare = function () {
   return function (req, res, next) {
       req._parsedUrl = 'SOME_THING';
       next()
   }
};

app.get('/', myMiddleWare, function (req, res) {
   console.log(req._parsedUrl); // SOME_THING
   res.end();
})

Express middleware document in here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.