javascript - Node js 不读取我的 CSS 文件

标签 javascript node.js

我正在尝试从 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

我的期望

enter image description here

我得到了什么

enter image description here

热烈感谢任何帮助

最佳答案

问题是您用 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/

相关文章:

node.js - 当 npm 安装或不安装 devDependency 时?

javascript - 提交表单时,如何检查用户的电子邮件是否已在我的数据库中?

javascript - 将文档对象参数传递给javascript中函数的正确方法

node.js - 为所有测试用例添加默认的 before() 函数 (Mocha)

javascript - $.when(ajaxCall) 与成功

javascript - AngularJS 基于键值对数组格式化数据

javascript - 我网站上的 Google 天气小部件

javascript - Pocket API 重新尝试授权用户时失败

Javascript 替换服务器返回的数据

javascript - 仅对来自服务器端的数据使用 eval() 是否安全? (如果没有,请提供替代方案)