NodeJS不能加载css文件

NodeJS can't load css file

本文关键字:文件 css 加载 不能 NodeJS      更新时间:2023-09-26

所以我想做一个NodeJS服务器,我尽量保持尽可能少的附加组件。

然而,我遇到了一个问题,我似乎无法加载我的HTML文件调用的任何CSS文件。这个调用似乎是由服务器处理的,但是它没有显示在浏览器中。

我的webserver.js文件

// A very basic web server in node.js
// Stolen from: Node.js for Front-End Developers by Garann Means (p. 9-10) 
var port = 8000;
var serverUrl = "localhost";
var http = require("http");
var path = require("path"); 
var fs = require("fs");         
console.log("Starting web server at " + serverUrl + ":" + port);
http.createServer( function(req, res) {
    var now = new Date();
    var filename = req.url || "index.html";
    var ext = path.extname(filename);
    var localPath = __dirname;
    var validExtensions = {
        ".html" : "text/html",          
        ".js": "application/javascript", 
        ".css": "text/css",
        ".txt": "text/plain",
        ".jpg": "image/jpeg",
        ".gif": "image/gif",
        ".png": "image/png",
        ".ico": "image/png"
    };
    var isValidExt = validExtensions[ext];
    if (isValidExt) {
        localPath += filename;
        fs.exists(localPath, function(exists) {
            if(exists) {
                console.log("Serving file: " + localPath);
                getFile(localPath, res, ext);
            } else {
                console.log("File not found: " + localPath);
                if(ext === 'text/html'){
                    getFile(__dirname + '/404.html', res, ext);
                }
            }
        });
    } else {
         console.log("Invalid file extension detected: " + ext)
         getFile(__dirname + '/index.html', res, 'text/html');
    }
}).listen(port, serverUrl);
function getFile(localPath, res, mimeType) {
    fs.readFile(localPath, function(err, contents) {
        if(!err) {
            res.setHeader("Content-Length", contents.length);
            res.setHeader("Content-Type", mimeType);
            res.statusCode = 200;
            res.end(contents);
        } else {
            res.writeHead(500);
            res.end();
        }
    });
}


index.html

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <p>
            Hello
        </p>
    </body>
</html>


style.css

p{
    color: red;
}


服务器日志

$ node webserver
Starting web server at localhost:8000
Serving file: c:'Users'MichaelTot'Desktop'Code Projects'Web'nodeJS/index.html
Serving file: c:'Users'MichaelTot'Desktop'Code Projects'Web'nodeJS/style.css


客户端日志

Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://127.0.0.1:8000/style.css".

问题就在这里:

getFile(localPath, res, ext);

您将ext赋给getFile,但根据函数签名,您正在等待mimetype。所以你应该这样做:

getFile(localPath, res, validExtensions[ext]);

浏览器不读取css,因为默认情况下NodeJS使用text/plain mime类型。但是浏览器想要一个text/css mime类型的css文件