[ 筆記 ] Express 04 - 工具安裝懶人包


Posted by krebikshaw on 2020-10-13

紀錄 Express 後端開發所需要安裝的指令及設定

快速安裝 - 濃縮版

☞ CLI 安裝

// express
npm init
npm install express --save
npm install ejs
// sequelize
npm install --save sequelize
npm install --save mysql2
npm install --save sequelize-cli
npx sequelize-cli init
// middleware
npm install body-parser
npm install express-session
npm install connect-flash
npm install bcrypt
npm install cors
// mkdir
mkdir controllers
mkdir views
mkdir public
// touch
touch index.js

☞ 建立 Models

☞ 設定 config.json 連線資料庫帳號

"development": {
  "username": "root",
  "password": null,
  "database": "post",
  "host": "127.0.0.1",
  "dialect": "mysql"
}

☞ 建立 table
CLI

npx sequelize-cli model:generate --name User --attributes username:string,password:string
npx sequelize-cli model:generate --name Prize --attributes name:string,imageURL:string,description:string,probability:integer,is_deleted:integer

☞ 設定 association
./models/xx.js

User.hasMany(models.Comment);
Comment.belongsTo(models.User);

./migrations/xx.js

UserId: {
  allowNull: false,
  type: Sequelize.INTEGER
},
CategoryId: {
  allowNull: false,
  type: Sequelize.INTEGER
}

☞ 執行 Migrations
CLI

//  npx sequelize-cli db:migrate:undo
npx sequelize-cli db:migrate
./node_modules/.bin/sequelize db:migrate

☞ 設定 index.js

const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const flash = require('connect-flash');
const cors = require('cors');

const app = express();
const port = 3001;

const xxController = require('./controllers/xx');
const ooController = require('./controllers/oo');

app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(flash());

app.set('trust proxy', 1);
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  // cookie: { secure: true }
}));

app.use((req, res, next) => {
  res.locals.username = req.session.username;
  res.locals.errorMessage = req.flash('errorMessage');
  next();
});

app.get('/', xxController.index);
app.get('/getApi', cors(), xxController.getApi);

function redirectBack(req, res) {
  res.redirect('back');
}

app.get('/add', xxController.add);
app.post('/add', xxController.handleAdd);

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

☞ 設定 ./controllers/xx.js

const bcrypt = require('bcrypt');
const db = require('../models');

const User = db.User;
const saltRounds = 10;

const userController = {
  login: (req, res) => {
    res.render('login');
  },
  handleLogin: (req, res, next) => {
    const { username, password } = req.body;
    if (!username || !password) {
      req.flash('errorMessage', '帳號或密碼錯誤!');
      return next();
    }
    User.findOne({
      where: {
        username
      }
    }).then(user => {
      if (!user) {
        req.flash('errorMessage', '帳號或密碼錯誤!');
        return next();
      }
      bcrypt.compare(password, user.password, (err, isSuccess) => {
        if (err || !isSuccess) {
          req.flash('errorMessage', '帳號或密碼錯誤!');
          return next();
        }
        req.session.username = user.username;
        req.session.userId = user.id;
        res.redirect('/');
      });
    }).catch(err => {
      req.flash('errorMessage', err.toString());
      return next();
    });
  },
  handleRegister: (req, res, next) => {
    const { username, password, nickname } = req.body;
    if (!username || !password || !nickname) {
      req.flash('errorMessage', '缺少必要欄位');
      return next();
    }

    bcrypt.hash(password, saltRounds, (err, hash) => {
      if (err) {
        req.flash('errorMessage', err.toString());
        return next();
      }
      User.create({
        username,
        nickname,
        password: hash
      }).then(user => {
        req.session.username = username;
        req.session.userId = user.id;
        res.redirect('/');
      }).catch(err => {
        req.flash('errorMessage', err.toString());
        return next();
      });
    });
  },
  handleLogout: (req, res) => {
    req.session.username = null;
    req.session.userId = null;
    res.redirect('/');
  }
};

module.exports = userController;

按照步驟慢慢安裝 - 穩定版

☞ Express 安裝

CLI

$ npm init
$ npm install express --save
$ touch index.js

☞ 建立 app / 指定 port

index.js

const express = require('express');

const app = express();
const port = 3000;


app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

☞ 建立 View

CLI

$ npm install ejs

☞ 設定 Ejs

index.js

app.set('view engine', 'ejs');

☞ Sequelize 安裝

CLI

$ npm install --save sequelize
$ npm install --save mysql2

☞ Sequelize CLI 安裝

CLI

$ npm install --save sequelize-cli
$ npx sequelize-cli init

設定 config.json 連線資料庫帳號

☞ 建立 Model

CLI

// 改成自己 table 的資料內容
$ npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
$ npx sequelize-cli model:generate --name Comment --attributes content:string
$ npx sequelize-cli model:generate --name User --attributes username:string,password:string
$ npx sequelize-cli model:generate --name Prize --attributes name:string,imageURL:string,description:string,probability:integer,is_deleted:integer

☞ 設定 association

./models/xx.js

// 根據 table 資料去設定
User.hasMany(models.Comment);
Comment.belongsTo(models.User);

./migrations/xx.js

// 根據 table 資料新增關聯用欄位
UserId: {
  allowNull: false,
  type: Sequelize.INTEGER
},
CategoryId: {
  allowNull: false,
  type: Sequelize.INTEGER
}

☞ 執行 Migrations

CLI

// $ npx sequelize-cli db:migrate:undo
$ npx sequelize-cli db:migrate

☞ 引入 Models

./controllers/xx.js

const db = require('./models');
const User = db.User;
const Comment = db.Comment;

☞ 安裝 Middleware

CLI

$ npm install body-parser
$ npm install express-session
$ npm install connect-flash
$ npm install bcrypt

☞ 設定 Middleware

index.js

const bodyParser = require('body-parser');
const session = require('express-session');
const flash = require('connect-flash');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(flash());

app.set('trust proxy', 1);
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  // cookie: { secure: true }
}));

./controllers/User.js

const bcrypt = require('bcrypt');
const saltRounds = 10;

bcrypt.hash(password, saltRounds, (err, hash) => {
  if (err) {
    req.flash('errorMessage', err.toString());
    return next();
  }
  User.create({
    username,
    nickname,
    password: hash
  }).then(user => {
    req.session.username = username;
    req.session.userId = user.id;
    res.redirect('/');
  }).catch(err => {
    req.flash('errorMessage', err.toString());
    return next();
  });
});

bcrypt.compare(password, user.password, (err, isSuccess) => {
  if (err || !isSuccess) {
    req.flash('errorMessage', '帳號或密碼錯誤!');
    return next();
  }
  req.session.username = user.username;
  req.session.userId = user.id;
  res.redirect('/');
});

#Express







Related Posts

Day 3 - Control Flow & Logical Operator

Day 3 - Control Flow & Logical Operator

[Power BI] 讀書會 #4 Analysis Services 概念(3)

[Power BI] 讀書會 #4 Analysis Services 概念(3)

CH1-TCL入門

CH1-TCL入門


Comments