javascript - CSS 和 JS 未在 URL 中加载斜杠
问题描述
我正在本地构建一个 Node.js 服务器,它会在localhost:8080
. 登陆页面是一个名为index.html
. 如果我键入localhost:8080/index.html
,HTML 以及位于同一文件夹中的 CSS 文件 ( main.css
) 和 JavaScript ( )将正常加载。但是,如果我键入带有斜杠的相同 URL, as ,它只会加载 html,而不是 CSS 或 JS。我尝试进入 Chrome 中的 HTML 页面源并单击其中的 css 文件,它似乎在寻找一个文件(从浏览器的地址栏中可以看到),该文件显然不存在。出于某种原因,它似乎是一个目录。任何帮助都会很棒。main.js
index.html
localhost:8080/index.html/
localhost:8080/index.html/main.css
index.html
编辑:处理路由的服务器部分看起来像这样(我刚刚开始,我试图在不使用 Express.js 的情况下进行路由):
const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");
http.createServer(function(request, response) {
function writeContentType(headerText) {
response.setHeader("Content-Type", headerText);
}
let requestedPath = url.parse(request.url, true).pathname;
requestedPath = requestedPath.replace(/^\/+|\/+$/g, "");
requestedPath = requestedPath.replace(/\//g, "\\");
requestedPath = "\\" + requestedPath;
if (requestedPath === "\\") requestedPath = "\\index.html";
if (!fs.existsSync(__dirname + requestedPath)) {
console.log("file does not exist, requested path is " + __dirname + requestedPath);
writeContentType("text/html");
response.write("<h1>Error 404</h1><h2>Page not found</h2>");
response.end();
} else {
let responseFile = fs.readFileSync(__dirname + requestedPath, function(err) {
console.log(err);
});
if (responseFile) {
let fileExtension = path.extname(requestedPath);
switch(fileExtension) {
case ".html" : writeContentType("text/html"); break;
case ".css" : writeContentType("text/css"); break;
case ".js" : writeContentType("text/javascript"); break;
case ".svg" : writeContentType("image/svg+xml"); break;
case ".jpg" :
case ".jpeg" : writeContentType("image/jpeg"); break;
}
response.end(responseFile);
}
}
}).listen(8080);
想法是去掉开头和结尾的requestedPath
所有斜杠,用反斜杠替换里面的任何斜杠,因为我的文件系统在 windows 中,然后在开头添加一个反斜杠,然后在文件系统中查找文件。我可能会在这里违背很多最佳实践,我才刚刚开始。
解决方案
无论您在何处引用 JS 和 CSS 文件,请在前面使用“/”,以便始终在根目录中搜索文件。例如,
href="/styles.css"
始终使用 express.static 提供静态文件
推荐阅读
- typescript - 是否可以对类的公共方法应用类型约束?
- powershell - 如何在 PowerShell 的 Select-Object 中使用 Sort-Object 和 Where-Object?
- scala - 我们如何看待相同功能的不同实现
- c++ - 如何将 mex matlab 中的引用发送到 C++ 代码
- java - Spring Boot 如何将所有请求重定向到 Dispatcher Servlet?
- python - 如何从已经存在的集合中为 mongoengine 文档生成模型
- php - MongoDB安装:找不到'php.h'文件#include
- sorting - GraphQL 未按预期对土耳其日期字段进行排序
- c# - 使用 LINQ 在可观察集合上优化或转换以下 for 循环
- c++ - 模板和初始化类成员