【问题标题】:How to enqueue CSS and JS to a page on the fly with NodeJS app file如何使用 NodeJS 应用程序文件动态地将 CSS 和 JS 排入页面
【发布时间】:2018-10-30 09:48:06
【问题描述】:

我需要“即时”获取 HTML 页面,将 CSS 和 JS 文件排入队列,然后使用 NodeJS 应用程序文件在浏览器中显示它。我的意思是在通过 NodeJS 获取页面之前不更改页面的 HTML 代码。 CSS 和 JS 文件都与 NodeJS 应用程序文件位于同一文件夹中。

我正在尝试这种方式

var fs = require('fs');
var http = require('http');
http.createServer(function (req, res) {
if(req.url === '/favicon.ico') {
    res.writeHead(404);
    res.end();
    return;
}

var indexPageHTML = fs.readFileSync('index.html');
var indexPageHTML = indexPageHTML.toString();
var indexPageHTML = indexPageHTML.split('</head>')[0]+'<link rel="stylesheet" type="text/css" href="style.css"></head>'+indexPageHTML.split('</head>')[1];
var indexPageHTML = indexPageHTML.split('</body>')[0]+'<script src="my_client_script.js"></script></body></html>';

res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
res.end(indexPageHTML);
}).listen(80, 'localhost');

我的缩小版index.html

<!doctype html><html><head><meta charset="utf-8"><title>Homepage title</title>
<style>html,body{height:100%;}</style></head><body>
<header></header>
<main role="main"></main>
<footer></footer>
</body></html>

在浏览器中我得到了我需要的代码,但没有加载任何文件(没有应用 CSS 并且 JS 在页面上不起作用)并且在浏览器控制台中我得到了错误

Uncaught SyntaxError: Unexpected token

和警告

资源被解释为样式表,但以 MIME 类型传输 文本/html:“http://localhost/app_style.css”。

如何解决问题?

ps。我正在C:/User/Username 内的磁盘 C 上的本地计算机上使用 NodeJS

【问题讨论】:

  • 您在响应每个请求时都使用相同的HTML。甚至对 styles.css 的请求也在接收 HTML 内容。

标签: javascript node.js


【解决方案1】:

好的,我通过链接NodeJS can't load css file找到了答案

刚刚添加了代码

...
if(mimeType == 'text/html') {
    var contents = contents.toString();
    var contents = contents.split('</head>')[0]+'<link rel="stylesheet" type="text/css" href="style.css"></head>'+contents.split('</head>')[1];
    var contents = contents.split('</body>')[0]+'<script src="my_client_script.js"></script></body></html>';
}
res.end(contents);
...

到getFile() 函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2019-11-04
    相关资源
    最近更新 更多