紀錄、express 環境設定


Posted by s103071049 on 2021-08-23

環境安裝

  1. npm init
  2. npm install express --save // 使用 express 框架
  3. npm install ejs // 用 express 實作 views -> app.set('view engine', 'ejs')
  4. npm install mysql // 因為資料會動態新增,所以要跟資料庫拿資料,官方文件
  5. npm install express-session // 為了實作 login 功能
const session = require('express-session')
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}))
  1. npm install body-parser // 拿到 request body 裡面的資料 -> 可以使用 post
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
  1. npm install connect-flash
const flash = require('connect-flash')
app.use(flash())
// key value 設置訊息
req.flash('errorMessage', 'Password Incorrect') // 寫入資料
req.flash('errorMessage') // 拿出資料
  1. 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
  1. npm install --save sequelize // 用物件方式操作資料庫
  2. npm install --save mysql2 /////
  3. npm install --save sequelize-cli
  4. 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

  1. find all / find One
  2. 放指定條件

squelize 回傳的特定資料格式,可以對他做 method 的操作

  • model usage
  • association 產生關聯:belongsTo / hasMany
    include 後面接 model

sequelize cli

  • 環境設置
  1. npm install sequelize
  2. npm install --save sequelize-cli
  3. npx sequelize-cli init
  4. 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









Related Posts

金魚系列,排板篇

金魚系列,排板篇

[極短篇] JSONP

[極短篇] JSONP

[React 01] 環境建置

[React 01] 環境建置


Comments