简体   繁体   中英

Website on server is treating file paths differently than local version

using Localhost, my HTML/CSS/JQuery stack website works perfectly fine, however, when uploading to a server, things break. Specifically, the src paths from within the JavaScript files. After being uploaded, the index HTML can find the appropriate JS files through the script tags. However, from things go wrong from within those JS files that are linked...

Keeping things big picture, I have JS files that use paths to certain imgs, or other files. And those JS files are stored from within folders. So you have

.
├── index.html
|
├── js
│   └── components
│        └── functions.js
└── img
     └── circle.jpg

In index.html, functions.js is called. From within functions.js I have a path to a circle.jpg for example. On localhost the path is "../../img/circle.jpg" because it treats components folder as the current working directory (cwd) "you are in components folder working in the functions.js file, now go out and into img folder"

However, on the server, cwd is the root folder. I guess that is because function.js is called from index.html and because index.html is in the root so it says "to get to circle.jpg you have to go "img/circle.jpg"

WHY? This doesn't make sense, to have it work on the server I now have to change all my file paths from within the JS files. This apparently isn't an issue on the src paths in the HTML, because it recognizes the tags and runs the Javascript. It breaks when trying to find the imgs based on the paths you give them. And it can't find the images in the JS based on those paths because of the above reasons. Instead of changing all the paths in the javascript how can I fix the imminent issue of the server treating the paths differently than the local version?

Add a < base href="" > tag in the head section of index.html

<head>
<base href="/">
<!-- other head items -->
</head>

If your index.html is the root path of the domain (like http: // someurl.com/index.html ), above should work. Or if the index.html is in a subfolder, provide the subfolder path as the href value. like,

<base href="/subfolder/">

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