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.
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.
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.
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.
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 ?
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.
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