這是我參與8月更文挑戰的第9天,活動詳情檢視: 8月更文挑戰
1. 安裝express
npm i express
複制代碼
2. Express的Hello,World
const express = require('express');
const app = express();
app.get('/',(req,res) => {
res.send('Hello,Express!');
})
app.listen(3000,() => {
console.log('伺服器啟動成功!');
})
複制代碼
3. 将一個檔案夾下的所有檔案變為可通路
app.use('/public',express.static('./public'));
複制代碼
4. 使用nodemon來儲存後自動重新開機
npm install nodemon -g
複制代碼
以後啟動一個檔案不再使用node + 檔案名的方式,而是使用nodemon + 檔案名的方式。這樣可以實作熱更新,即儲存就更新伺服器。
基本路由
app.get('/',(req,res) => {
res.send('Hello,Express666!');
})
app.get('/about',(req,res) => {
res.send('關于');
})
複制代碼
暴露檔案不同方式的差別
1. 隻有一個參數(URL可以直接通路檔案名)
app.use(express.static('./public'));
複制代碼
2. 兩個參數(URL必須包含指向改檔案的路徑)
app.use('/public',express.static('./public'));
複制代碼
3. 别名的形式
app.use('/a',express.static('./public'));
複制代碼
這裡的a意思是路徑中以a開頭的,就可以通路public路徑下的檔案。
在express中配置模闆引擎art-template
1. 安裝art-template
npm install --save art-template
npm install --save express-art-template
複制代碼
2. API介紹
當渲染以.art結尾的檔案的時候,使用art-template模闆引擎
app.engine('art', require('express-art-template'));
//或者,下面的這種方式也是可以的
app.engine('html', require('express-art-template'));
複制代碼
調用res.render的時候,會預設去項目的views目錄中查找指定的檔案,但是該檔案必須以art結尾。如果engine中的第一個參數是html,則不需要進行重命名,即下面的第二種方式。
app.get('/',(req,res) => {
res.render('404.art');
})
// 方式二
app.get('/',(req,res) => {
res.render('404.html');
})
複制代碼
修改預設的views目錄
app.set('views','test');
複制代碼
一個基于express的留言本小案例
const express = require('express');
const app = express();
let comments = [
{
name: '黃多多',
message: '爸爸去哪了',
dateTime: '2020-5-21'
},
]
app.engine('html', require('express-art-template'));
app.get('/', (req, res) => {
res.render('index.html',{
comments
});
})
app.get('/post', (req, res) => {
res.render('post.html');
})
app.get('/pinglun',(req,res) => {
let comment = req.query;
comment.dateTime = new Date().toLocaleString();
comments.unshift(comment);
res.redirect('/');
})
// 開放public目錄
app.use('/public', express.static('public'));
app.listen(3000, () => {
console.log('伺服器在3000端口啟動成功......');
})