4.靜態(tài)文件
#4.1.普通處理靜態(tài)文件的方法
在./views/index.html文件中去引入另一個(gè)css文件index.css,index.css文件放在public/css目錄下,目錄結(jié)構(gòu)是這樣的
image
index.html文件中的內(nèi)容
<!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">
<title>Document</title>
<style>
#wrap {
width: 300px;
margin: 100px auto;
line-height: 150px;
height: 150px;
text-align: center;
background-color: green;
}
#wrap a {
color: white;
text-decoration: none;
}
</style>
<link rel="stylesheet" href="/public/css/index.css">
</head>
<body>
<div id="wrap">
<a href="/login">登錄 | </a>
<a href="/user">用戶中心</a>
</div>
</body>
</html>
根據(jù)請(qǐng)求渲染出index.html文件
app.get('/', function (req, res) {
res.sendFile('./index.html')
})
當(dāng)我們方法 '/'這個(gè)路徑的時(shí)候刽肠,能把index.html頁(yè)面加載出來(lái)房铭,但是沒(méi)辦法把css文件加載出來(lái)
image
為了解決這個(gè)問(wèn)題,我們還需要單獨(dú)去寫一個(gè)路由去返回css文件
app.get('/public/css/index.css', function (req, res) {
res.sendFile(path.resolve('./public/css/index.css'))
})
#4.2.express中處理靜態(tài)文件的插件
express中提供了處理靜態(tài)文件的插件,這里的靜態(tài)文件就是我們項(xiàng)目中需要用到的img治拿、css、js等資源,只需要簡(jiǎn)單的配置就可以實(shí)現(xiàn)對(duì)靜態(tài)文件的處理,步驟如下:
第一步攒盈,在app中掛載插件
app.use(express.static('./public'))
第二步,使用靜態(tài)文件,在index.html文件中引入css哎榴,路徑需要修改一下
<link rel="stylesheet" href="/css/index.css">