我正在尝试从 Node Js 服务器脚本读取 html 文件,但它没有读取我在 html 文件中链接的 css 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My node file</title>
<link rel = "stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class = "home">
<h2>Hello there</h2>
<p>Iam developing my first node js site</p>
</div>
</body>
</html>
我的CSS
.home{
background: red;
}
我的 Node.js 文件
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080
我的期望
我得到了什么
热烈感谢任何帮助
最佳答案
问题是您用 index.html
回答每个请求。这意味着如果 Web 浏览器发送对 style.css
的请求,它仍然会获取 html。您可以查看浏览器控制台来验证这一点。要提供不同的文件,您可能需要检查 request.url
准确地提供客户想要的文件:
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
if(req.url === "/index.html" || req.url === "/"){
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
} else if(req.url === "/style.css"){
fs.readFile('style.css', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
}
}).listen(8080);
如果您认为这对于许多不同的文件来说很麻烦,您可以使用允许静态目录服务的库,例如express
关于javascript - Node js 不读取我的 CSS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475068/