'Difference between Localhost and opening html file

What is the fundamental difference running a file using a server in localhost, and opening a file such as file:///Users/$user_name/$your_directory/index.html, assuming no backend is used, and it is only frontend and contains html/css/js
How does this also affect interactions with other server ie. ajax requests?
I am sorry if this is too broad, but I haven't found a solid answer to these underlying questions.



Solution 1:[1]

Fundamentally, assuming at some point you're going to host the result on an actual web server, the former matches the target environment while the latter doesn't. Browsers treat local files and files served from web servers (even localhost web servers) differently, although very similarly. One aspect of this is the encoding: When you retrieve a file from a web server, the process of determine what encoding the data is in is different from opening a local file.

How does this also affect interactions with other server ie. ajax requests?

This is one of the primary ways in which they're handled differently, and it even varies from browser to browser. A page loaded from a file:// URL has origin null from a Same Origin Policy standpoint. Some browsers (like Chrome) disallow Cross-Origin Resource Sharing entirely for origin null, even when the server you're trying to talk to has a wide-open CORS policy (*). Others (like Firefox) allow origin null to match the wildcard.

In general, for best results, ensure that your development environment matches your deployment environment in the important ways. That means doing your development using a web server process rather than local files. Most IDEs will happily provide that process for you; if not, Apache or Nginx aren't hard to install.

Solution 2:[2]

answer is simple, if u don't have made active backend yet for "index.html" then it would not effect.e.g.-"localhost" and "index.html" will be same this time.

but when u start working with the backend,then most of the backend processes need an active server (need localhost).

e.g.- 1. fetch('local.json')... //fetch json or any file would not work for local files. 2. u may not ineract with mysql/django etc. databases. means it cause errors in signup/login , store any image/video/docs at database etc.

so better is work in localhost, it's most easy way is :-

VScode(IDE) >> extenctions >> live server (just need to click a button to make 
localhost and click again to stop localhost)

https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jizhihaoSAMA