我是 NodeJS 的初学者,在加载 CSS 时遇到问题。这是我的代码。
我只是创建一个在 9090
端口运行的服务器并加载默认的 HTML
文件。
var server = http.createServer(function(request, response) {
var html = fs.readFileSync('./FirstApp/HtmlPages/index.html');
response.writeHead(200,{"Content-Type": "text/html"});
response.write(html);
response.end();
});
server.listen(9090);
在加载 http://localhost:9090/
时,我可以看到 index.html
html 页面,但看不到链接的 css
功能。(如果我只是在浏览器中加载我的 index.html
,我可以看到 css
功能,但不能通过服务器看到)
这是我的简单 HTML。
<html>
<head>
<link type="text/css" rel="stylesheet" href="./css/styles.css">
</head>
<body>
<h2 class="heading"><em>Login Page</em></h2>
</body>
</html>
CSS
文件
.heading {
text-align: center;
}
我可以在浏览器控制台看到下面的警告
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:9090/css/styles.css".
任何帮助将不胜感激
最佳答案
问题是您创建了一个仅提供单个文件 index.html 的 Web 服务器。它不从本地文件系统读取任何 CSS 文件,也不提供任何 CSS 文件。
您可以分析传入的请求并查看请求的 URL 路径是否指向 CSS 文件。如果是,则读取 CSS 文件而不是 HTML 文件并将其与响应一起返回。
这是您的代码的一个有效修改版本(假设 styles.css 位于您的 index.html 所在目录的子目录中):
var server = http.createServer(function(request, response) {
if (request.url.match(/^\/css\//)) {
var css = fs.readFileSync('./FirstApp/HtmlPages' + request.url);
response.writeHead(200,{"Content-Type": "text/css"});
response.write(css);
response.end();
return;
}
var html = fs.readFileSync('./FirstApp/HtmlPages/index.html');
response.writeHead(200,{"Content-Type": "text/html"});
response.write(html);
response.end();
});
server.listen(9090);
请注意:我这样做只是为了学习目的,而不是为了构建实际的生产网络应用程序。为此,我会使用现有的 HTTP 服务器解决方案,例如 Express .
关于html - 无法使用 NodeJS 加载 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48960354/