我已经使用中间件加载了静态CSS文件,但无法正常工作。当我简单地打开不带服务器的html / ejs文件时,将加载CSS。但是,当我使用快递服务器执行相同操作时,它不起作用。
在开发人员工具的网络部分中,css文件显示404错误。
快递代码:
//express
const express = require('express');
const app = express();
const path = require('path');
app.set('view engine' , 'ejs');
//middleware
app.use(express.static(path.join(__dirname, 'public')));
//home route
app.get('/' , (req , res) =>{
res.render('todosample');
});
//listning to port
app.listen(8080);
文件结构为:
public
todosamplestyle.css
views
todosample.ejs
app.js
HTML文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="../public/todosamplestyle.css">
<title>Greatest To-do ever</title>
</head>
<body>
<header>
<span>Greatest To-Do Ever</span>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Me</a></li>
</ul>
</nav>
</header>
<main>
<form action="#">
<input type="text" class="form-control form-control-lg" name="search" id="">
<input class="btn btn-primary" value="Add Item">
</form>
</main>
<div class="items">
<ul class="list-group list-group-flush">
<li class="list-group-item">Cras justo odio<button class="btn btn-outline-danger">X</button></li>
<li class="list-group-item">Dapibus ac facilisis in<button class="btn btn-outline-danger">X</button></li>
<li class="list-group-item">Morbi leo risus<button class="btn btn-outline-danger">X</button></li>
<li class="list-group-item">Porta ac consectetur ac<button class="btn btn-outline-danger">X</button></li>
<li class="list-group-item">Vestibulum at eros<button class="btn btn-outline-danger">X</button></li>
</ul>
</div>
</body>
</html>
答案 0 :(得分:0)
您正在使用express.static
上的/
共享CSS文件。因此,您的CSS文件的路径为:http://host:port/todosamplestyle.css
您正在渲染/
路线。这意味着您的CSS路径将为./todosamplestyle.css
如果您想在静态变量前加上/public
,则可以通过
app.use('/public', express.static('public'))