如何使用 node、express 和 ejs 包含 css 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24582338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I include css files using node, express, and ejs?
提问by stealthysnacks
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. I've gone into the developer's console noticed the type is set to 'text/html' instead of 'text/css'.
既不加载 css。我进入了开发人员的控制台,注意到类型设置为“text/html”而不是“text/css”。
My path looks like
我的路径看起来像
.
./app.js
./public
/css
/style.css
回答by Arunkumar
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" />
回答by Eric Nderitu
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 i.e
<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!!
繁荣。它的工作!
回答by White Lantern
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
.
之所以出现错误,是因为您在 之后使用了逗号而不是 concat + __dirname
。
回答by 2rahulsk
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">
回答by Aft3rL1f3
IMHO answering this question with the use of ExpressJS is to give a superficial answer. 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'.
恕我直言,用 ExpressJS 回答这个问题,是给出一个肤浅的答案。我将在不使用任何框架或模块的情况下尽可能地回答。通常使用框架来回答这个问题的原因是因为它消除了理解“超文本传输协议”的要求。
- The first thing that should be pointed out is that this is more a problem surrounding "Hypertext-Transfer-Protocol" than it is Javascript. When request are made the url is sent, aswell as the content-type that is expected.
- 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. This question refers to CSS so we will keep our focus there. In a tag that links a CSS file to an HTML file there are 3 properties. rel="stylesheet" type="text/css" and href="http://localhost/..." for this example we are going to focus on type and 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.
- 首先应该指出的是,这更多是围绕“超文本传输协议”的问题,而不是 Javascript。发出请求时,会发送 url 以及预期的内容类型。
- 要了解的第二件事是请求来自哪里。最初,人们会请求一个 HTML 文档,但根据文档中所写的内容,文档本身可能会向服务器发出请求,例如:图像、样式表等。这个问题与 CSS 相关,所以我们将重点放在那里。在将 CSS 文件链接到 HTML 文件的标签中,有 3 个属性。rel="stylesheet" type="text/css" 和 href="http://localhost/..." 对于这个例子,我们将关注类型和 href。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. I tested it and it worked. Remember that index.css and index.html can be swapped with any html/css files you want.
这是我可能会单独请求的一种方式的快速示例。现在请记住,这是一个快速示例,通常会在 severfiles 之间拆分,其中一些将具有作为对其他函数的依赖的功能,但是对于“简而言之”的麻袋,这是我能做的最好的事情。我测试了它并且它起作用了。请记住 index.css 和 index.html 可以与您想要的任何 html/css 文件交换。
回答by Kqt
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 然后将所有静态文件放入其中
回答by sonu singh
I have used the following steps to resolve this problem
我已使用以下步骤来解决此问题
- create new folder (static) and move all js and css file into this folder.
- then add app.use('/static', express.static('static'))
- add css like < link rel="stylesheet" type="text/css" href="/static/style.css"/>
- restart server to view impact after changes.
- 创建新文件夹(静态)并将所有 js 和 css 文件移动到此文件夹中。
- 然后添加app.use('/static', express.static('static'))
- 添加像<link rel="stylesheet" type="text/css" href="/static/style.css"/> 这样的 css
- 重新启动服务器以查看更改后的影响。
回答by Dhananjaya
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;
and don't change anything in CSS linking.
很简单,如果您正在使用,express.static(__dirname + 'public')
请不要忘记在 public 之前放置一个正斜杠,express.static(__dirname + '/public')
或者使用express.static('public')
它也可以工作;并且不要更改 CSS 链接中的任何内容。
回答by devyJava
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.
上面的回答有一半有效,我不是为什么它们不在我的机器上,但我必须执行以下操作才能使其正常工作。
- Created a directory at the root
/public/js/
- Paste this into your server.js file with name matching the name of directory created above. Note adding
/public
as the first paramapp.use('/public',express.static('public'));
- Finally in the HTML page to which to import the javascript file into,
<script src="public/js/bundle.js"></script>
- 在根目录创建一个目录
/public/js/
- 将其粘贴到您的 server.js 文件中,其名称与上面创建的目录名称相匹配。注意添加
/public
为第一个参数app.use('/public',express.static('public'));
- 最后在要将 javascript 文件导入的 HTML 页面中,
<script src="public/js/bundle.js"></script>