简体   繁体   中英

Server host and port for front-end JavaScript

I am a newb web dev and I simply don't know how the front-end javascript knows what the host and port is of its respective server. I never told the front end that info but it just knew by default - how is that the case? For example, my front-end JavaScript program is talking to my server at localhost:3000. But there is nothing in the JavaScript code that tells the program that the server is located at localhost:3000.

So as one answer suggests, it must be the default because that information was provided to the browser when the user navigated to the URL, so it might be stored in window.location.

Also as one answer suggests, if you want your front-end to talk to a server that is not located at the URL of the page you navigated to, you probably have to use CORS https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

The browser via Ajax can only connect to the same addres the page is from. So each request is send to the same server:port the page comes from.

If you want to do something fancy you need to move to jsonp or similar.

The default Port for web is 80.

In your server configuration you can set this.

The browser assumes that correct port is 80 for http. Other protocols have different default ports.

You can specify the port you want the browser to reach by using : , like so -

http://example.com:8080 - Will try to reach port 8080 of the web address

It is due to the window.location object of javaScript.

window.location.hostname provides the hostname, eg, www.mysite.com

window.location.port provides the port name

window.location.protocol provides the protocol used, eg, http:, https: etc

there are other properties too in window.location object. Check this

Is this what you are asking??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM