为了学习Web开发人员,我正在从事一个个人项目,但遇到了一个奇怪的问题(希望可以轻松解决)。在我的index.html文件中,我包含了对main.js文件的引用,并且现在已经工作了一段时间了。但是,我最近用Typescript重写了该项目,并决定重新安排文件夹结构。问题是,当我将index.html文件(和其他一些文件)移到一个目录下并将'../'附加到脚本的'src'标记时,当html尝试加载脚本时出现404错误
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>
使用第二种方案时连接到站点会出现此错误:
GET http://localhost:8000/scripts/Main.js net::ERR_ABORTED 404 (Not Found)
是否不允许index.html在其自己的目录上方查看?是否存在权限问题?这是一件很简单的事情,无法正常工作,我想我一定缺少一些小东西。
预先感谢您的帮助!
答案 0 :(得分:0)
找到了答案!
将index.html移回根目录后,问题不在我的html或main.js中,但在快速服务器中,我正在使用:
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 + ")");
});
基本上,我已经正确地更改了html文件的路径,但是我也忘记在app.use()中进行更改。将该行更改为app.use(express.static(__dirname + "/.."));
可解决此问题。
答案 1 :(得分:-2)
这应该很简单,只需将index.html文件移到两个文件结构之外
|-scripts
|-Main.ts
|-Main.js
|-SlideShowView.ts
|-SlideShowView.js
|-services
|-Server.ts
|-Server.js
|-index.html -> <script src="scripts/Main.js" type="module"></script>