【发布时间】: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