【发布时间】:2022-01-05 12:59:43
【问题描述】:
当我在用 node.js 编写的本地服务器上运行我的 HTML 文件时,我在 HMTL 文件中链接的 CSS 文件不起作用。
我的 javascript 代码
const http=require('http');
const fs=require('fs');
http.createServer(function(req,res){
fs.readFile("index.html",(error,data)=>{
res.writeHead(200,{'Content-Type':'text/html'});
res.write(data);
return res.end();
})
}).listen(8080);
我的 HTML 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type=text/css href="./css/desktop.css">
<title>CODESTER-TrackYourProgress</title>
</head>
<body>
...
</body>
</html>
我的 CSS 文件位于 css 文件夹中,名称为 desktop.css。
【问题讨论】:
-
你试过 fs.readFile('./index.html', ... ) 吗??
-
您的网络服务器使用 HTML 文件的内容响应每个请求。您没有编写任何除此之外的任何代码,所以这是唯一正在发生的事情。您需要查看
req变量并根据请求包含的内容向浏览器提供不同的文件。