本週重點
- Express 是可以在 Node.js 環境下執行的輕量後端框架,自由度極高,也能夠快速開發出後端應用程式。
- 試試看能不能快速上手 Express 並完成作業。
- ORM(Object Relational Mapping)-> Sequelize
簡單來說就是把一個程式碼裡面的物件跟資料庫的物件做映射(mapping),優點就是當你操作程式裡的物件時,就會改到資料庫裡的資料。 - 部署到 Heroku或是自己的主機(nginx + PM2)。
Node.js 實作一個 Server
( 底層透過 http.createServer 建立 Server )
- index.js
const http = require('http') // node.js 內建 http 相關的 module
const server = http.createServer(handler) // http.createServer(function)
function handler(req, res){ // node.js 會給兩個參數 req、res
console.log(req.url)
res.write('hello!')
res.end() // 把 res 丟回去(結束)
}
server.listen(5001) // 最常 80 part
- 終端機上執行
node index.js
- 瀏覽器網址打開
localhost:5001
- 終端機上跑出
/favicon.ico
就是網頁標題旁邊的那個小 logo
標準點的寫法會加上:
res.writeHead(200, {
'Content-Type': 'text/html' // 瀏覽器就知道你想要解析的格式,但有些瀏覽器很聰明會自己幫我們解析
})
在 node 中增加靜態檔案 & 路徑讀取
expressjs__static
Node.js 中的 __dirname
、__filename
const absolutePath = path.join(__dirname, '../lib/common.js')
or
app.use('/static', express.static(__dirname + '/public'));
Express
- 新增一個資料夾
- terminal
npm init
npm install express
- index.js
const express = require('express')
const app = express()
const port = 5001
app.get('/', (req, res) => {
res.send('hello')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`)
})
然後 terminal run -> node index.js
-> localhost:5001 就會出現 Hello 了
補充
用 Express 製作簡易的留言版
Introduction · Node.js 從無到有,打造一個漂亮乾淨俐落的 RESTful API (gitbooks.io) 試起來!
跟 LAMP 差別
Apache + PHP Process
瀏覽器 -> Apache Sercer -> PHP
瀏覽器 <- Apache Sercer <- PHP
Express Process
瀏覽器 -> Express Server
瀏覽器 <- Express Server
What is MVC?
之前快速筆記過關於 MVC 的定義
- Model:模型,負責處理資料、演算法、商業邏輯等等。
- View:視圖:欲呈現的畫面。
- Controller:控制器,控制、處理使用者的請求(request)。
Controller 跟 Model 拿 data -> 拿完 Controller 把 data 塞去 View,就變完整的 response 了(template+data)-> 回傳回去
ejs
terminal npm install ejs
Middleware
app.use((req, res, next) => {
next()
})
bodyParser
拿 request body 裡面的資料
body parsing middleware
npm install body-parser
const bodyParser = require('body-parser')
app.use(bodyParse.urlencoded({ extend: false }))
app.use(bodyParser.json())
Express session
npm install express-session
session middleware
做登入登出功能
app.use(session({
secret: 'keynoard cat',
resave: false,
saveUninitalized: true
app.use(function (req, res, next){
if(!req.session.views){
req.session.views = {}
}
})
}))
connect-flash
res.locals
重複物件自己做一個 middleware 變全域,res.locals view 都可以拿到
index.js
app.use((req, res, next) => { // 自己做 middleware,就不用一直寫重複物件
res.locals.isLogin = req.session.isLogin || false
res.locals.errorMessage = req.flash('errorMessage')
next()
})
做 hash
npm install bcrypt
ORM Object Relational Mapping
本來在操作資料庫裡的東西 (SQL query) 把他看成物件(Object),
所以用操縱 Object 的方式來操作資料
Sequelize
方法文件裡寫的蠻清楚,多多熟悉就好!
npm install --save sequelize
npm install --save mysql2
npm install --save sequelize-cli
npx sequelize-cli init
npx 可以用 ./node_modules/.bin/sequelize 指令代替(npx 就是這個位置,但有時
後跑比較慢)
./node_modules/.bin/sequelize model:generate --name User --attributes username:string,password:string,nickname:string
./node_modules/.bin/sequelize model:generate --name Comment --attributes content:text
./node_modules/.bin/sequelize db:migrate
./node_modules/.bin/sequelize db:migrate:undo
Sequelize 裡的資料庫關聯
.hasOne
.hasMany
ex.
User.hasMany(Comment) -> 單向關聯到 Comment
Comment.belongsTo(User) -> 建立雙向關係
Heroku
Heroku
其他類似平台:Google GAE、新浪云 SAE 不過在這之前都沒聽過,只聽過 Heroku
- 環境變數
Proxy Server
- 代理伺服器:把 client 真實身份藏起來
- Reverse Proxy 反向代理
- 當網站入口 -> 80port 上放就可以連到不同 server
- Nginx 就是 Reverse Proxy Server