NodeJS无法加载css文件

时间:2015-10-22 12:23:58

标签: javascript html css node.js

所以我试图创建一个NodeJS服务器,并尽量保留尽可能少的附加组件。

但是,我遇到了问题,我似乎无法加载CSS文件调用的任何HTML文件。该呼叫似乎由服务器处理,但它不会在浏览器中显示。

我的 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".

1 个答案:

答案 0 :(得分:4)

问题在于:

"*"

您将getFile(localPath, res, ext); 提供给ext,但根据功能签名,您正在等待mimetype。所以你应该这样做:

getFile

浏览器无法读取css,因为默认情况下NodeJS使用getFile(localPath, res, validExtensions[ext]); mimetype。但浏览器需要一个text/plain mimetype作为css文件。