节点js没有读取我的CSS文件 [英] Node js not reading my CSS file

查看:123
本文介绍了节点js没有读取我的CSS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从节点Js服务器脚本中读取一个html文件,但它没有读取我在html文件中链接的css文件

Am trying to read an html file from node Js server script but its not reading a css file which i linked in the html file

<!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;
}

我的节点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浏览器发送<$ c $请求c> style.css 它仍然获取html。您可以查看浏览器控制台以验证这一点。要提供不同的文件,您可能需要检查 request.url 准确提供客户端文件想要:

The problem is that you answer every request with index.html. That means if the web browser sends a request for style.css it still gets the html. You could look into your browsers console to verify this. To serve different files, you might wanna check request.url to serve exactly the file the client wants to:

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);

如果您认为许多不同的文件变得讨厌,您可以使用允许静态目录服务的库,例如快递

If you think that gets nasty for many different files, you may use a library that allows static directory serving, e.g. express

这篇关于节点js没有读取我的CSS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆