Home > Software engineering >  how fetch api knows relative url?
how fetch api knows relative url?

Time:09-27

static javascript files are downloaded from server to client browser and runs there right?

if I have a .js file with contents below,

fetch("/api/users")

I believe this resolves to full URL of its server's domain or IP address. (such as https://my.server.com/api/users)

But how does this script knows that itself came from host my.server.com and therefore should prefix with that host name?

I mean, scripts are just independent files and does not know about environment it is running at.

CodePudding user response:

But how does this script knows that itself came from host my.server.com and therefore should prefix with that host name?

It's part of the specification of the fetch API, specifically:

  1. Let baseURL be this’s relevant settings object’s API base URL.

Which itself links off to various other places defining 3 different things specifying those.

In short, it's not anything the scripts themselves that are running are doing - it's the implementation of fetch that's doing it, whether that's provided by the browser, or a serverside runtime such as Node etc.

  • Related