【问题标题】:Nodejs: Served html page not linked to cssNodejs:服务的html页面未链接到css
【发布时间】:2012-08-31 09:48:05
【问题描述】:

我在 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 - 我知道有些软件包可以让我盲目地执行此操作(例如“连接”),但我试图在走这条路之前了解实际发生的情况。

【问题讨论】:

    标签: html css node.js


    【解决方案1】:

    我在使用 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}));
    

    这使用express.static。就我而言,我从 Foundation 框架提供静态 css 和 js,但您可以轻松地将其修改为特定的 public 文件夹。

    【讨论】:

      【解决方案2】:

      问题大概出在这一行:

       fs.readFile('js/EmailDisplay/htm/index.html', function(error, content) {
      

      即使在请求.js.css 时,您也正在读取并向客户端返回相同的html 文件。

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

      【讨论】:

      • 搞定了,非常感谢!我是一个学习曲线非常陡峭的 javascript/node/html/css 菜鸟。来自 Matlab,我仍然只是意识到 nodejs(没有包)是多么低级,以及路径是多么重要。
      猜你喜欢
      • 2021-08-21
      • 1970-01-01
      • 2017-12-10
      • 2017-05-03
      • 1970-01-01
      • 2015-03-28
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多