【问题标题】:Serving css files with nodejs使用 nodejs 提供 css 文件
【发布时间】:2020-09-25 18:22:50
【问题描述】:

我是 node js 的新手,我试图简单地为一个包含 html 和 css 文件的站点提供服务。我写了下面的代码

var http = require('http');
var fs = require('fs');

http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(fs.readFileSync('./style.css', {encoding: "utf8"}));
    res.write(fs.readFileSync('./index.html', {encoding: "utf8"}));
    res.end();
}).listen(3000);

console.log('server running @ 3000');

当我启动服务器时,这“有效”意味着我可以在考虑 css 的同时看到网站渲染,但是 css 文本被写在我的网站底部,就像它在 div 标签内的嵌入文本一样。谁能解释我为什么看到这个?另外,由于我是 nodejs 的新手,任何关于在我的服务器上提供 css 或 JS 文件的建议都将不胜感激。

【问题讨论】:

  • css 文件是动态生成的,大部分 css 文件会在 html 文件中引用,您将只提供一个 html 文件
  • 你为什么要这么做?你不能直接在 index.html 中链接 css 吗?

标签: javascript node.js


【解决方案1】:

我已经修改了您的代码(正在运行)。看看吧:

var http = require('http');
var fs = require('fs');

http.createServer((req, res) => {
    console.log(req.url)
    if (req.url === "/") {
        fs.readFile('index.html', (err, html) => {
            if (err) {
                throw err;
            }
            res.setHeader('Content-type', 'text/html');
            res.write(html);
            res.statusCode = 200;
            res.end();
        });
    }
    else if (req.url == '/style.css') {
        res.setHeader('Content-type', 'text/css');
        res.write(fs.readFileSync('style.css'));
        res.end();
    } else {
        res.write("invalid request")
        res.end();
    }
}).listen(3000);

console.log('server running @ 3000');

这是 HTML 文件:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="/style.css" />
  </head>
  <body>
    Hello
  </body>
</html>

和 style.css

body {
  color: red;
}

您需要根据您的要求退回文件。例如,在这种情况下,HTML 文件向服务器请求/style.css,服务器查看代码并找到处理该请求的块

 else if (req.url == '/style.css') {
            res.setHeader('Content-type', 'text/css');
            res.write(fs.readFileSync('style.css'));
            res.end();
        } 

最后返回文件。我希望这会有所帮助。

推荐:

使用 express.js (https://expressjs.com/)。 它是遵循 MVC 模式的 NodeJS 路由框架,非常快速且易于使用。 youtube 和 google 上有很多关于这个框架的资源。

【讨论】:

  • 谢谢!这就像一个魅力,我还能够应用相同的格式来提供我的 js 文件,我的网站现在正在运行。你想让主路由异步是有道理的,因为那个路由会调用链接样式表和 js 文件的其他请求,我说得对吗?此外,我注意到很多内容在标准节点上推送 express,并将朝着这个方向发展,但想先体验一下节点。
  • 是的,你可以在异步等待语法中做到这一点。
猜你喜欢
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 2020-09-11
  • 2017-05-10
相关资源
最近更新 更多