ste*_*cks 33 css ejs node.js express
我正在尝试按照说明/sf/answers/1304367921/,但我仍然无法加载我的styles.css.
来自app.js
app.use(express.static(path.join(__dirname, 'public')));
Run Code Online (Sandbox Code Playgroud)
在我的.ejs中,我尝试过这两行
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<link rel="stylesheet" type="text/css" href="/public/css/style.css" />
Run Code Online (Sandbox Code Playgroud)
既没有加载CSS.我已经进入开发人员的控制台注意到类型设置为'text/html'而不是'text/css'.
我的路径看起来像
.
./app.js
./public
/css
/style.css
Run Code Online (Sandbox Code Playgroud)
Aru*_*mar 76
在server.js文件中使用它
app.use(express.static(__dirname + '/public'));
Run Code Online (Sandbox Code Playgroud)
并添加CSS如
<link rel="stylesheet" type="text/css" href="css/style.css" />
Run Code Online (Sandbox Code Playgroud)
不需要/之前的css喜欢
<link rel="stylesheet" type="text/css" href="/css/style.css" />
Run Code Online (Sandbox Code Playgroud)
小智 22
1.如果不存在,则创建一个名为“public”的新文件夹。
2.在新创建的'public'文件夹下新建一个名为'css'的文件夹
3.在public/css路径下创建你的css文件
4.在你的html链接css上
<link rel="stylesheet" type="text/css" href="/css/style.css">
// 注意href 之前使用了斜杠(/),您不需要包含'public'
5.在你的 app.js 中包括:
app.use(express.static('public'));
繁荣。它的工作!
我们拥有的自定义样式表是本地文件系统中的静态页面。为了让服务器提供静态文件,我们必须使用,
app.use(express.static("public"));
Run Code Online (Sandbox Code Playgroud)
在哪里,
public 是我们必须在根目录中创建的文件夹,它必须有其他文件夹,如 css、images.. 等
目录结构如下:
然后在您的 html 文件中,将 style.css 引用为
<link type="text/css" href="css/styles.css" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)
对于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}...`);
}
});
Run Code Online (Sandbox Code Playgroud)
小智 5
在您的主.js文件中使用:
app.use('/css',express.static(__dirname +'/css'));
Run Code Online (Sandbox Code Playgroud)
在您的主.html文件中使用:
<link rel="stylesheet" type="text/css" href="css/style.css" />
Run Code Online (Sandbox Code Playgroud)
之所以出现错误,是因为您在 之后使用了逗号而不是 concat + __dirname。
| 归档时间: |
|
| 查看次数: |
100882 次 |
| 最近记录: |