Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What javascript library sets the _parsedUrl property on a request object

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.

like image 277
mjk Avatar asked May 17 '16 19:05

mjk


People also ask

How to parse a URL in JavaScript?

The URL () constructor is handy to parse (and validate) URLs in JavaScript. new URL (relativeOrAbsolute [, absoluteBase]) accepts as first argument an absolute or relative URL.

What is the return value of url parse?

Return Value: The url.parse () method returns an object with each part of the address as properties. If urlString is not a string then it threw TypeError. If auth property exists but not decoded then it threw URIError. Example 2: This example illustrates the properties of url object.

What is a property in JavaScript?

JavaScript Properties Properties are the values associated with a JavaScript object. A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted, but some are read only.

What is a URL object in JavaScript?

The URL object immediately allows us to access its components, so it’s a nice way to parse the url, e.g.: Here’s the cheatsheet for URL components: search – a string of parameters, starts with the question mark ?


1 Answers

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.

like image 153
analog-nico Avatar answered Oct 04 '22 18:10

analog-nico