[英]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我已使用以下步骤来解决此问题
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'.
通常使用框架来回答这个问题的原因是因为它消除了理解“超文本传输协议”的要求。
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.上面的回答有一半有效,我不是为什么它们不在我的机器上,但我必须执行以下操作才能使其正常工作。
/public/js/
/public
as the first param/public
作为第一个参数
app.use('/public',express.static('public'));
<script src="public/js/bundle.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.