NodeJS无法加载CSS文件 [英] NodeJS can't load css file

查看:211
本文介绍了NodeJS无法加载CSS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试制造NodeJS服务器,并尝试保留尽可能少的附件.

So I'm trying to make a NodeJS server, and I try to keep as few add-ons as possible.

但是,我遇到了一个问题,我似乎无法加载我的 HTML 文件调用的任何 CSS 文件.呼叫似乎确实已由服务器处理,但没有显示在浏览器中.

However, I have hit a problem, I don't seem to be able to load any CSS files called by my HTML files. The call do seem to be processed by the server, but it doesn't show in the browser.

我的 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 ,但是根据功能签名,您正在等待模仿类型.所以你应该这样做:

You give ext to getFile, but according to the function signature, you are waiting for the mimetype. So you should do this :

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

浏览器不会读取CSS,因为默认情况下,NodeJS使用 text/plain 模仿类型.但是浏览器需要CSS文件的 text/css 模仿类型.

The browser don't read the css because by default NodeJS use the text/plain mimetype. But the browser wants a text/css mimetype for a css file.

这篇关于NodeJS无法加载CSS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆