简体   繁体   中英

HTML <script> src url no longer works after rearranging files

I'm working on a personal project in order to learn web dev, and I've run into a strange (and hopefully easily solved) problem. In my index.html file I've included a reference to a main.js file, and that's been working just fine for a while now. However, I've recently rewritten the project in Typescript and I've decided to rearrange the folder structure. The problem is that when I move my index.html file (and some other files) down one directory and append a '../' to the script's 'src' tag, I get a 404 error when the html attempts to load the script.

This works just fine:  
.  
|-scripts  
     |-Main.ts  
     |-Main.js  
     |-SlideShowView.ts  
     |-SlideShowView.js  
|-Server.ts  
|-Server.js  
|-index.html -> <script src="scripts/Main.js" type="module"></script> 



This does not:
.  
|-scripts  
     |-Main.ts  
     |-Main.js  
     |-SlideShowView.ts  
     |-SlideShowView.js  
|-services
     |-Server.ts  
     |-Server.js  
     |-index.html -> <script src="../scripts/Main.js" type="module"></script> 

Connecting to the site when using the second scheme gives this error:
GET http://localhost:8000/scripts/Main.js net::ERR_ABORTED 404 (Not Found)
Is index.html not allowed to look above it's own directory? Is there a permissions issue or something? It's such a simple thing that's failing to work I figure there must be something small I'm missing.

Thanks in advance for the help!

Found the answer!

After I moved index.html back to root, the problem wasn't in my html or main.js, but in the express server I was using:

import path from "path";  
import express from "express";  

const serverPortNum = 8000;  
const htmlFile = path.join(__dirname + '/../index.html'); //Added an escape here...  

// Create html server  
var app = express();  
app.use(express.static(__dirname));// ...but not here.   
app.get('/', function(req: any, res: any)  
{  
  res.sendFile(htmlFile);  
});  

app.listen(serverPortNum, function()  
{  
  console.log("Listening! (port " + serverPortNum + ")");  
});  

Basically, I had changed the path to the html file correctly but I forgot to make the change in app.use() as well. Changing that line to app.use(express.static(__dirname + "/..")); corrected the problem.

This should be simple as moving the index.html file outside of both file structures

|-scripts  
     |-Main.ts  
     |-Main.js  
     |-SlideShowView.ts  
     |-SlideShowView.js  
|-services
     |-Server.ts  
     |-Server.js  
|-index.html -> <script src="scripts/Main.js" type="module"></script>

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