4lackof
4lackof

Reputation: 1390

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 /MyLoginUrl or /MyUpdateDataUrl, 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 argument 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:

baseURLstring: 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 baseURLstring is:

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 baseURLstring for, currently, localhost and eventually when this gets hosted by the main server I will use for my network, the baseURLstring 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...

Upvotes: 0

Views: 33

Answers (2)

Irfan Anwar
Irfan Anwar

Reputation: 1918

baseURLstring will the url of your website, lets take the example of Google: base url of google is https://www.google.com similarly your baseurlstring will be something like this https://www.yourwebsiteaddress.com and the first parameter in url = new URL(urlString, [baseURLstring]) is the path of the files placed on your server (root folder, where your default index file is placed)

Upvotes: 0

Y.Berrama
Y.Berrama

Reputation: 101

you can test this

var base_url = location.protocol + '//' + location.host + '/';

Upvotes: 1

Related Questions