简体   繁体   English

如何使用 node、express 和 ejs 包含 css 文件?

[英]How can I include css files using node, express, and ejs?

I'm trying to follow the instructions to https://stackoverflow.com/a/18633827/2063561 , but I still can't get my styles.css to load.我正在尝试按照https://stackoverflow.com/a/18633827/2063561的说明进行操作,但我仍然无法加载 style.css。

From app.js来自 app.js

app.use(express.static(path.join(__dirname, 'public')));

In my .ejs, I have tried both of these lines在我的 .ejs 中,我已经尝试了这两行

<link rel="stylesheet" type="text/css" href="/css/style.css" />
<link rel="stylesheet" type="text/css" href="/public/css/style.css" />

Neither loads the css.既不加载 css。 I've gone into the developer's console noticed the type is set to 'text/html' instead of 'text/css'.我进入了开发人员的控制台,注意到类型设置为“text/html”而不是“text/css”。

My path looks like我的路径看起来像

.
./app.js
./public
    /css
        /style.css

Use this in your server.js file在你的 server.js 文件中使用它

app.use(express.static(__dirname + '/public'));

and add css like并添加 css 之类的

<link rel="stylesheet" type="text/css" href="css/style.css" />

dont need / before css like不需要 / 在 css 之前

<link rel="stylesheet" type="text/css" href="/css/style.css" />

1.Create a new folder named 'public' if none exists. 1.如果不存在,则创建一个名为“public”的新文件夹。

2.Create a new folder named 'css' under the newly created 'public' folder 2.在新创建的'public'文件夹下新建一个名为'css'的文件夹

3.create your css file under the public/css path 3.在public/css路径下创建你的css文件

4.On your html link css ie <link rel="stylesheet" type="text/css" href="/css/style.css"> 4.在你的 html 链接 css 上,即<link rel="stylesheet" type="text/css" href="/css/style.css">

// note the href uses a slash(/) before and you do not need to include the 'public' // 注意href 之前使用了斜杠(/),您不需要包含'public'

5.On your app.js include : app.use(express.static('public')); 5.在你的 app.js 中包括: app.use(express.static('public'));

Boom.It works!!繁荣。它的工作!

The custom style sheets that we have are static pages in our local file system.我们拥有的自定义样式表是本地文件系统中的静态页面。 In order for server to serve static files, we have to use,为了让服务器提供静态文件,我们必须使用,

app.use(express.static("public"));

where,在哪里,

public is a folder we have to create inside our root directory and it must have other folders like css, images.. etc public 是我们必须在根目录中创建的文件夹,它必须有其他文件夹,如 css、images.. 等

The directory structure would look like :目录结构如下:

在此处输入图片说明

Then in your html file, refer to the style.css as然后在您的 html 文件中,将 style.css 引用为

<link type="text/css" href="css/styles.css" rel="stylesheet">

For NodeJS I would get the file name from the res.url , write the header for the file by getting the extension of the file with path.extname , create a read stream for the file, and pipe the response.对于我的NodeJS将从获取文件名res.url ,通过获取与文件的扩展名写的文件头path.extname ,创建文件的读数据流和管道的响应。

const http = require('http');
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 3000;

const server = http.createServer((req, res) => {
    let filePath = path.join(
        __dirname,
        "public",
        req.url === "/" ? "index.html" : req.url
    );

    let extName = path.extname(filePath);
    let contentType = 'text/html';

    switch (extName) {
        case '.css':
            contentType = 'text/css';
            break;
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.json':
            contentType = 'application/json';
            break;
        case '.png':
            contentType = 'image/png';
            break;
        case '.jpg':
            contentType = 'image/jpg';
            break;
    }

    console.log(`File path: ${filePath}`);
    console.log(`Content-Type: ${contentType}`)

    res.writeHead(200, {'Content-Type': contentType});

    const readStream = fs.createReadStream(filePath);
    readStream.pipe(res);
});

server.listen(port, (err) => {
    if (err) {
        console.log(`Error: ${err}`)
    } else {
        console.log(`Server listening at port ${port}...`);
    }
});

Use in your main .js file:在您的主.js文件中使用:

app.use('/css',express.static(__dirname +'/css'));

use in you main .html file:在您的主.html文件中使用:

<link rel="stylesheet" type="text/css" href="css/style.css" />

The reason you getting an error because you are using a comma instead of a concat + after __dirname .之所以出现错误,是因为您在__dirname之后使用了逗号而不是 concat +。

I have used the following steps to resolve this problem我已使用以下步骤来解决此问题

  1. create new folder (static) and move all js and css file into this folder.创建新文件夹(静态)并将所有 js 和 css 文件移动到此文件夹中。
  2. then add app.use('/static', express.static('static'))然后添加app.use('/static', express.static('static'))
  3. add css like < link rel="stylesheet" type="text/css" href="/static/style.css"/>添加像<link rel="stylesheet" type="text/css" href="/static/style.css"/> 这样的 css
  4. restart server to view impact after changes.重新启动服务器以查看更改后的影响。

IMHO answering this question with the use of ExpressJS is to give a superficial answer.恕我直言,用 ExpressJS 回答这个问题,是给出一个肤浅的答案。 I am going to answer the best I can with out the use of any frameworks or modules.我将在不使用任何框架或模块的情况下尽可能地回答。 The reason this question is often answerd with the use of a framework is becuase it takes away the requirment of understanding 'Hypertext-Transfer-Protocall'.通常使用框架来回答这个问题的原因是因为它消除了理解“超文本传输​​协议”的要求。

  1. The first thing that should be pointed out is that this is more a problem surrounding "Hypertext-Transfer-Protocol" than it is Javascript.首先应该指出的是,这更多是围绕“超文本传输​​协议”的问题,而不是 Javascript。 When request are made the url is sent, aswell as the content-type that is expected.发出请求时,将发送 url 以及预期的内容类型。
  2. The second thing to understand is where request come from.要了解的第二件事是请求来自哪里。 Iitialy a person will request a HTML document, but depending on what is written inside the document, the document itsself might make requests of the server, such as: Images, stylesheets and more.最初,人们会请求一个 HTML 文档,但是根据文档中所写的内容,文档本身可能会向服务器发出请求,例如:图像、样式表等。 This question refers to CSS so we will keep our focus there.这个问题与 CSS 相关,所以我们将重点放在那里。 In a tag that links a CSS file to an HTML file there are 3 properties.在将 CSS 文件链接到 HTML 文件的标签中,有 3 个属性。 rel="stylesheet" type="text/css" and href="http://localhost/..." for this example we are going to focus on type and href. rel="stylesheet" type="text/css" 和 href="http://localhost/..." 对于这个例子,我们将关注类型和 href。 Type sends a request to the server that lets the server know it is requesting 'text/css', and 'href' is telling it where the request is being made too. Type 向服务器发送一个请求,让服务器知道它正在请求 'text/css',而 'href' 也告诉它请求是在哪里发出的。

so with that pointed out we now know what information is being sent to the server now we can now seperate css request from html request on our serverside using a bit of javascript.所以指出了这一点,我们现在知道哪些信息正在发送到服务器,现在我们可以使用一些 javascript 将 css 请求与我们服务器端的 html 请求分开。

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




    function onRequest(request, response){  
        if(request.headers.accept.split(',')[0] == 'text/css') {
             console.log('TRUE');

             fs.readFile('index.css', (err, data)=>{
                 response.writeHeader(200, {'Content-Type': 'text/css'});
                 response.write(data);
                 response.end();
             });  
        }

        else {
            console.log('FALSE');    

            fs.readFile('index.html', function(err, data){
                response.writeHead(200, {'Content_type': 'text/html'});
                response.write(data);
                response.end();
            });
        };
    };

    http.createServer(onRequest).listen(8888);
    console.log('[SERVER] - Started!');


Here is a quick sample of one way I might seperate request.这是我可能会单独请求的一种方式的快速示例。 Now remember this is a quick example that would typically be split accross severfiles, some of which would have functions as dependancys to others, but for the sack of 'all in a nutshell' this is the best I could do.现在请记住,这是一个快速示例,通常会在 severfiles 之间拆分,其中一些将具有作为对其他函数的依赖的功能,但是对于“简而言之”的麻袋,这是我能做的最好的事情。 I tested it and it worked.我测试了它并且它起作用了。 Remember that index.css and index.html can be swapped with any html/css files you want.请记住 index.css 和 index.html 可以与您想要的任何 html/css 文件交换。

In your app or server.js file include this line:在您的应用程序或 server.js 文件中包含以下行:

app.use(express.static('public'));

In your index.ejs, following line will help you:在您的 index.ejs 中,以下行将帮助您:

<link rel="stylesheet" type="text/css" href="/css/style.css" />

I hope this helps, it did for me!我希望这会有所帮助,它对我有用!

Use this in your server.js file在你的 server.js 文件中使用它

 app.use(express.static('public'));

without the directory ( __dirname ) and then within your project folder create a new file and name it public then put all your static files inside it没有目录( __dirname ),然后在您的项目文件夹中创建一个新文件并将其命名为 public 然后将所有静态文件放入其中

Its simple if you are using express.static(__dirname + 'public') then don't forget to put a forward slash before public that is express.static(__dirname + '/public') or use express.static('public') its also going to work;如果您使用express.static(__dirname + 'public')则很简单,然后不要忘记在 public 之前放置一个正斜杠,即express.static(__dirname + '/public')或使用express.static('public')它也可以工作; and don't change anything in CSS linking.并且不要更改 CSS 链接中的任何内容。

the order of registering routes is important .注册路由的顺序很重要。 register 404 routes after static files.在静态文件之后注册404路由。

correct order:正确的顺序:

app.use("/admin", admin);
...

app.use(express.static(join(__dirname, "public")));

app.use((req, res) => {
  res.status(404);
  res.send("404");
});

otherwise everything which is not in routes , like css files etc.. , will become 404 .否则所有不在路由中的东西,比如 css 文件等等,都会变成 404 。

The above responses half worked and I'm not why they didn't on my machine but I had to do the following for it work.上面的回答有一半有效,我不是为什么它们不在我的机器上,但我必须执行以下操作才能使其正常工作。

  1. Created a directory at the root在根目录创建一个目录

    /public/js/

  2. Paste this into your server.js file with name matching the name of directory created above.将其粘贴到您的 server.js 文件中,其名称与上面创建的目录名称相匹配。 Note adding /public as the first param注意添加/public作为第一个参数

    app.use('/public',express.static('public'));

  3. Finally in the HTML page to which to import the javascript file into,最后在要将 javascript 文件导入的 HTML 页面中,

    <script src="public/js/bundle.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM