小夥伴們你們好,我是大家的pubdreamcc
,接着前面的學習,這篇博文出至於個人GitHub倉庫:Node學習教程資料
,若是你以爲對你有幫助,歡迎star
,大家的點贊是我持續更新的動力,謝謝!javascript
Node.js學習教程資料:GitHubhtml
咱們在以前的node.js學習的基礎課程中已經完成了一個簡單的用戶發表評論社區,今天咱們利用web開發框架--express
來重寫案例,進一步增強對express
框架的理解和使用。java
npm
初始化項目在本地任意目錄下建立名爲:expressCommentList
文件夾,cd文件夾中,運行:npm init -y
快速初始化,生成package.json
文件。安裝相應第三方依賴:node
npm install express art-template express-art-template body-parser --save
咱們在expressCommentList
文件夾中建立一個名爲:public
文件夾,用來存放靜態文件,也就是公開的資源文件。項目中用到的bootstrap
樣式文件和頁面的腳本文件等均可以放到public
文件夾中。git
一樣地,在expressCommentList
文件夾中建立名爲:views
文件夾,views
文件夾用來存放頁面視圖相關的文件,這也爲後面模板引擎默認查找模板文件的位置一致,便於後續編碼。github
app.js
爲咱們的服務器文件,在這裏咱們使用express
來開啓一個web服務器。web
app.js
文件中核心代碼以下:shell
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
對於express-art-template
和body-parser
在express中的具體用法,不清楚的夥伴能夠關注個人以前Node教程資料:express中art-template的使用
和express中獲取post請求數據
,這裏就再也不贅述。npm
若是須要完整demo代碼,能夠查看GitHub上倉庫Node學習demo案例
文件夾,固然若是你有好的建議也能夠issue我,或者留言評論,thank you!