4lackof 4lackof - 1 year ago 59
Javascript Question

JS - baseURLString when sending pathnames only

I am trying to create a

new URL
in JS so it can be manipulated for an async request. As nothing is cross-origin (I think this is the correct usage of that term), the URLs I send for async request look like
or /
, etc. (i.e. I am only sending the pathname).

My attempt to create a
new URL
from an existing url looked basically like this:

// Actually I set the url as an arguement in a function,
// but for demonstration it will be a variable
var url = '/myPathname';

// Much later...
url = new URL (url);

However, this was returning a syntax error. Once I looked a docs, I found out why.

Per the docs, the syntax for a
new URL
looks like this:

url = new URL(urlString, [baseURLstring])

url = new URL(urlString, baseURLobject)

The docs also say:

: is a DOMString representing the base URL to use in case urlString is a relative URL. If not specified, and no baseURLobject is passed in parameters, it default to 'about:blank'. If it is an invalid absolute URL, the constructor will raise a DOMException of type SYNTAX_ERROR

A couple of examples in the docs for a

var a = new URL("/", "https://developer.mozilla.org"); // Creates a URL pointing to 'https://developer.mozilla.org/'
var b = new URL("https://developer.mozilla.org"); // Creates a URL pointing to 'https://developer.mozilla.org/'
var c = new URL('en-US/docs', b); // Creates a URL pointing to 'https://developer.mozilla.org/en-US/docs'

Thus, I am trying to figure out how to emulate a
for, currently,
and eventually when this gets hosted by the main server I will use for my network, the
for that. I'm guessing it would involve in some way getting the IP address of the computer I have/of the server on the network, or maybe not...

Answer Source

you can test this

var base_url = location.protocol + '//' + location.host + '/';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download