html - Node.js 不会发送 CSS 作为响应

标签 html css node.js

我正在尝试使用 node.js 设置客户端/服务器程序。 我有以下代码,它在连接时返回一个 .html 文件。

JavaScript:

var http = require('http');
const fs = require('fs');
var server;

fs.readFile('./FrontPage.html', function (err, html){
if (err){
    throw err;
}

server = http.createServer(function (req, res) {
    res.writeHead(200, {
        "Content-Type": "text/html"
    });
    res.write(html);
    res.end();
    console.log("HTTP response sent");
});

var port = 3000;
server.listen(port, function () {
    console.log("Server listening on port " + port);
}); 
});

HTML:

<head>
    <link rel="stylesheet" type="text/css" href="./css/FrontPageCSS.css">
</head>



<body style="background-image:url(./img/bg.jpg)">

<div id="header">
        <a href="./frontPage.html"><img src="./img/Logo.png" height="5%" width="5%" alt="logo"></a>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="./script/FrontPageJS.js"></script>
</div>

<div id="buttonWrapper">
    <div id="first" class="first">
        This is my first button
    </div>

    <div id="second" class="second">
        This is my second button
    </div>
</div>

当我在浏览器中访问端口 3000 上的 localhost 时,它返回没有 CSS 的 .html 文件。当我通过它的路径单独打开 .html 时,CSS 工作正常。

我的问题:为什么 CSS 没有包含在响应中,我该如何包含它?

最佳答案

CSS 文件不包含在 HTML 中。 它们在 HTML 解析期间由浏览器下载。

您的示例不起作用,因为当浏览器尝试获取 css/FrontPageCSS.css 时,它会获取 HTML 输出,因为您的服务器始终响应 FrontPage.html 文件的内容。

我建议你使用一些 web 框架作为 express:http://expressjs.com/en/index.html

关于html - Node.js 不会发送 CSS 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34071030/

相关文章:

node.js - Node + Express 路由器 + 类型脚本 : string arg is not assignable to requesthandlerparams type

javascript - 如何使用 GET 方法通过 XMLHttpRequest 传递 FormData

html - CSS - 背景停止

node.js - 如何在 Node js 应用程序中使用 azure-cli Node 包

node.js - 使用 Node.JS 上传到 Flickr : Invalid auth_token

jQuery animate.css 仅在 Firefox 上无法正常工作

php - 我正在尝试使用 post 方法将变量从 PHP 传递到 HTML,但它对我不起作用

javascript - wow.js 和 fullpage.js 动画触发同时滚动到/离开视口(viewport)

css - 当 <div> 的位置设置为 relative 时 <nav> 栏消失

JavaFX 滚动条自定义。当两个滚动条都被激活时,消除多余的正方形