Nodejs:提供的html页面未链接到css

Nodejs:提供的html页面未链接到css,html,css,node.js,Html,Css,Node.js,我在nodejs中运行了以下基本脚本,以提供一个带有相关css样式表的html文件: var http = require('http'); var fs = require('fs'); var path = require('path'); var serverPort = 8080; var server = http.createServer(function(request, response) { console.log('request starting ...'); var

我在nodejs中运行了以下基本脚本,以提供一个带有相关css样式表的html文件:

var http = require('http');
var fs = require('fs');
var path = require('path');

var serverPort = 8080;

var server = http.createServer(function(request, response) {

console.log('request starting ...');
var extname = path.extname(request.url);

var contentType = 'text/html';
    switch (extname) {
    case '.js':
        contentType = 'text/javascript';
        break;
    case '.css':
        contentType = 'text/css';
        break;
    }

fs.readFile('js/EmailDisplay/htm/index.html', function(error, content) {
    if (error) {
        console.log(error);
        response.writeHead(500);
        response.end();
    } else {
        console.log(contentType);
        response.writeHead(200, {'Content-Type': contentType});
        response.end(content,'utf-8');
    }
});
});

server.listen(serverPort);
console.log('Server running at localhost:' + serverPort +"/");
如果我在Firefox中打开文件(文件->打开文件),它会正确渲染。如果我转到localhost:8080,将提供索引页,但没有应用于它的样式。为什么?fs.readFile块中的console.log向我显示正在读取这两个文件


PS-我知道有些软件包会让我盲目地这样做(例如“连接”),但我正在尝试在走这条路线之前了解实际发生的情况。

问题可能在于这一行:

 fs.readFile('js/EmailDisplay/htm/index.html', function(error, content) {
即使在请求
.js
.css
时,您也在读取并返回相同的html文件


您可能应该在代码前面的开关中设置文件的路径及其内容类型。

我在nodejs和express中遇到了同样的问题。请参见下面我的示例
server.js

var express= require("express");
var app= express();
app.get("/", function(request, response) {
    response.sendFile("testing.html", {root: "."});
});
app.listen(8080);
可以通过包括以下行来添加静态内容:

app.use(express.static("foundation-5.4.6", {index: false}));

这使用了。在我的例子中,我从框架中提供静态css和js,但您可以轻松地将其修改到特定的
public
文件夹中。

工作正常,非常感谢!我是一个javascript/node/html/css noob,学习曲线非常陡峭。来自Matlab,我仍然只是认识到低级节点(w/o包)是多么的重要,路径是多么的重要。