寫在前面
小伙伴們大家好,我是你們的pubdreamcc
,接着前面的學習,這篇博文出至於我的GitHub倉庫:Node學習教程資料
,如果你覺得對你有幫助,歡迎star
,你們的點贊是我持續更新的動力,謝謝!
Node.js學習教程資料:GitHub
前言
我們在之前的node.js學習的基礎課程中已經完成了一個簡單的用戶發表評論社區,今天我們利用web開發框架--express
來重寫案例,進一步加強對express
框架的理解和使用。
demo主體
- 創建項目文件夾,
npm
初始化項目
在本地任意目錄下創建名為:expressCommentList
文件夾,cd文件夾中,運行:npm init -y
快速初始化,生成package.json
文件。安裝相應第三方依賴:
npm install express art-template express-art-template body-parser --save
- 創建靜態資源文件夾
我們在expressCommentList
文件夾中創建一個名為:public
文件夾,用來存放靜態文件,也就是公開的資源文件。項目中用到的bootstrap
樣式文件和頁面的腳本文件等都可以放到public
文件夾中。
- 創建頁面視圖文件夾
同樣地,在expressCommentList
文件夾中創建名為:views
文件夾,views
文件夾用來存放頁面視圖相關的文件,這也為后面模板引擎默認查找模板文件的位置一致,便於后續編碼。
- 創建服務器文件
app.js
為我們的服務器文件,在這里我們使用express
來開啟一個web服務器。
demo主要代碼
app.js
文件中核心代碼如下:
const express = require('express')
// 引入body-parser
const bodyParser = require('body-parser')
const app = express()
// 開放靜態資源
app.use('/public/', express.static('./public'))
// 配置express-art-template模板引擎
app.engine('html', require('express-art-template'))
// 配置body-parser
app.use(bodyParser.urlencoded({ extended: false }))
// 先造一些假數據,供模板引擎渲染
let comments = [
{
name: 'jack',
content: 'hello world',
time: '2019-5-1'
},
{
name: 'Tom',
content: 'hello world',
time: '2019-5-1'
},
{
name: 'dream',
content: 'hello world',
time: '2019-5-1'
},
{
name: 'james',
content: 'hello world',
time: '2019-5-1'
},
{
name: 'jack',
content: 'hello world',
time: '2019-5-1'
},
{
name: 'life',
content: 'hello world',
time: '2019-5-3'
}
]
app.get('/', (req, res) => {
res.render('index.html', {
comments: comments
})
})
app.get('/post', (req, res) => {
res.render('post.html')
})
app.post('/comment', (req, res) => {
// 得到post請求發送的數據
const comment = req.body
comment.time = '2019-5-21'
comments.unshift(comment)
// 重定向到首頁(‘/’)
res.redirect('/')
})
app.listen(3000, () => {
console.log('running...')
})
這里使用了express-art-template
模板引擎渲染模板文件,並且通過express的中間件:body-parser
來獲取表單POST提交后的數據,最終通過把POST提交的數據合並到原始數據中即可顯示在首頁上。
對於express-art-template
和body-parser
在express中的具體用法,不清楚的伙伴可以關注我的之前Node教程資料:express中art-template的使用
和express中獲取post請求數據
,這里就不再贅述。
demo演示效果圖
如果需要完整demo代碼,可以查看GitHub上倉庫Node學習demo案例
文件夾,當然如果你有好的建議也可以issue我,或者留言評論,thank you!