首页 > 解决方案 > 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.jsindex.htmllocalhost:8080/index.html/localhost:8080/index.html/main.cssindex.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 中,然后在开头添加一个反斜杠,然后在文件系统中查找文件。我可能会在这里违背很多最佳实践,我才刚刚开始。

标签: javascriptnode.js

解决方案


  1. 无论您在何处引用 JS 和 CSS 文件,请在前面使用“/”,以便始终在根目录中搜索文件。例如,

    href="/styles.css"

  2. 始终使用 express.static 提供静态文件


推荐阅读