環境安裝
- npm init
- npm install express --save // 使用 express 框架
- npm install ejs // 用 express 實作 views ->
app.set('view engine', 'ejs')
- npm install mysql // 因為資料會動態新增,所以要跟資料庫拿資料,官方文件
- npm install express-session // 為了實作 login 功能
const session = require('express-session')
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
- npm install body-parser // 拿到 request body 裡面的資料 -> 可以使用 post
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
- npm install connect-flash
const flash = require('connect-flash')
app.use(flash())
// key value 設置訊息
req.flash('errorMessage', 'Password Incorrect') // 寫入資料
req.flash('errorMessage') // 拿出資料
- npm install bcrypt // 密碼 hash
const bcrypt = require('bcrypt')
const saltRounds = 10
主程式
- app.use( ) / next( ) -> 舉例:權限檢查
- res.locals,裡面的東西可以在 view 裡面拿到
app.use((req, res, next) => {
res.locals.isLogin = req.session.isLogin || false
res.locals.errorMessage = req.flash('errorMessage')
next()
})
squelize and orm
- getting statrted -> installing
- npm install --save sequelize // 用物件方式操作資料庫
- npm install --save mysql2 /////
- npm install --save sequelize-cli
- npx sequelize-cli init
- setting up a connection
Modeling a table + model definition
Synchronizing all models at once
Synchronizing the model with the database
getting started Querying + Querying
- find all / find One
- 放指定條件
squelize 回傳的特定資料格式,可以對他做 method 的操作
- model usage
- association 產生關聯:belongsTo / hasMany
include 後面接 model
sequelize cli
- 環境設置
- npm install sequelize
- npm install --save sequelize-cli
- npx sequelize-cli init
- npm install --save mysql2
- Creating the first Model (and Migration)
Let's create a model named User.
We have just created required model and migration files for our first model User.
npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
// 建立 model 與 migration 兩個檔案,model 慣例大寫
Now to actually create that table in database you need to run db:migrate command.
npx sequelize-cli db:migrate