1. 程式人生 > 其它 >React + Koa2打造『官方管理後臺』2

React + Koa2打造『官方管理後臺』2

技術標籤:實戰專案reactnodejs

四.admin表模型、密碼加密、初始化admin賬戶

1.測試redisclient,控制器中

const {redisSet,redisGet}= require('../lib/redisClient') ;
class Index{
    async index(ctx,next){
        const sess = ctx.session;
        if(!sess.uid){
            sess.uid = 1;
            sess.userName = 'zza';
            sess.nikeName = 'js++';
            sess.gender = 'male'
        }
       redisGet('txclass.sessCNDoPmbqF8SyH1xCTQf4kHAnhy4x4Z6y').then((res)=>{
           console.log(res);
       })
       console.log(sess)
        ctx.body={
            session:sess
        }
    }
}
module.exports = new Index();

把以上程式碼註釋

2.初始化admin,model中建立admin.js

const seq = require('../connection/mysql_connect'),
   { STRING,INT ,TEXT} = require('../../config/db_type_config');
const Admin = seq.defin('admin',{
    username:{
        comment:'admin user name',
        type:STRING,
        allowNull:false
    },
    passWord:{
        comment:'crypto user password',
        type:STRING,
        allowNull:false
    }
})   
module.exports= Admin;

3.入口檔案引入

Admin = require('./admin')
module.exports={
    Slider,AgencyInfo,RecomCourse,Collection,Teacher,Student,CourseTab,Course,Aboutus,Admin
}

4.更改sync.js

去除force 這樣就不會覆蓋其他表,同時同步表模型

5.新建admin.js控制器

const {adminInfo} = require('../config/config');
class Admin {
    async createAdmin(){}
}
module.exports = new Admin();

6.config.js中新增初始賬戶

 adminInfo:{
        username:'admin',
        password:'admin'
    }

7.新建admin.js路由

const router = require('koa-router')(),
adminController = require('../controller/admin')
router.prefix('/admin')
router.get('/create_admin',adminController.createAdmin)
module.exports = router;

8.appjs中註冊

const adminRouter = require('./routes/admin')
app.use(adminRouter.routes(), adminRouter.allowedMethods())

9.新建service中admn.js

const AdminModel = require('../do/models/admin');
class AdminService {
    async addAdmin(data){
        const {username} = data;
        const result = await AdminModel.findOne({
            where:{username}
        });
        if(result){
            return await AdminModel.update(data,{
                where:{username}
            })
        }else{
            return await AdminModel.create(data);
        }
    }
}
module.exports=new AdminService();

10.controll中

const {adminInfo} = require('../config/config'),
      {addAdmin} = require('../service/admin');
class Admin {
    async createAdmin(){
        const result = await addAdmin(adminInfo);
        if(result){
            console.log(0);
        }else{
            console.log(1);
        }
    }
}
module.exports = new Admin();

11.訪問路由,資料入表

12.整理utils,增加方法

config中增加配置

cryptoSecret:'[email protected]#$jklaf1234'

utils中把方法提取出去

        crypto = require('crypto'),
    { qiniu, cryptoSecret } = require('../config/config'),
function makeCrypto(str){
    const _md5 = crypto.createHash('md5'),
          content = `str=${str}&secret=${cryptoSecret}`;
    return _md5.update(content).digest('hex')      
}
module.exports = {
    startProcess, qiniuUpload,makeCrypto
}  

13.controll中進行引入加密

const {adminInfo} = require('../config/config'),
      {addAdmin} = require('../service/admin'),
      {makeCrypto} = require('../lib/util');
class Admin {
    async createAdmin(){
        adminInfo.password = makeCrypto(adminInfo.password)
        const result = await addAdmin(adminInfo);
        if(result){
            console.log(0);
        }else{
            console.log(1);
        }
    }
}
module.exports = new Admin();

14.重新整理,資料入表

五.建立與配置React專案

1.安裝腳手架工具

npm i create-react-app -g

建立檔案,在檔案中新建專案

create-react-app todo

啟動方式

npm start

2.改造結構

刪除繁文縟節的內容

3.安裝sass

npm i node-sass -S

4.配置別名,weebpack.config

node_modules\react-scripts\config\webpack.config.js搜尋alias

alias: {
        // Support React Native Web
        // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
        'react-native': 'react-native-web',
        // Allows for better profiling with ReactDevTools
        ...(isEnvProductionProfile && {
          'react-dom$': 'react-dom/profiling',
          'scheduler/tracing': 'scheduler/tracing-profiling',
        }),
        ...(modules.webpackAliases || {}),
        '@':path.appSrc,
        'pages':path.appSrc+'/pages',
        'components':path.appSrc+'/components',
        'assets':path.appSrc+'/assets',
        'services':path.appSrc+'/services',
        'utils':path.appSrc+'/utils'
      },

5.安裝router

npm i react-router-dom -S

6.配置iconfont

oneOf: [
            // "url" loader works like "file" loader except that it embeds assets
            // smaller than specified limit in bytes as data URLs to avoid requests.
            // A missing `test` is equivalent to a match.
            {
              test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
              loader: require.resolve('url-loader'),
              options: {
                limit: imageInlineSizeLimit,
                name: 'static/media/[name].[hash:8].[ext]',
              },
            },
            {
              test:/\.(woff2?|eot|ttf|oft|svg)(\?.*)?$/i,
              loader:[
                'url-loader?name=fonts/[name].[ext]'
              ]
            },

六.建立react路由、巢狀路由的配置

1.安裝router

npm i react-router -S

2.pages中新建index.js和login.js

快捷鍵rcc

index

import React, { Component } from 'react'

export default class index extends Component {
   constructor(props){
        super(props)
        this.state={}
        
    }
    render() {
        return (
            <div>
                Index Page
            </div>
        )
    }
}

login

import React, { Component } from 'react'

export default class login extends Component {
   constructor(props){
        super(props)
        this.state={}
        
    }
    render() {
        return (
            <div>
                login Page
            </div>
        )
    }
}

app.js

import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom'
import { Route, Switch, NavLink, Link } from 'react-router-dom'
import IndexPage from './pages/index'
import LoginPage from './pages/login'


function App() {
  return (
    <Router>
      <Switch>
        <Route component={LoginPage} path="/login"></Route>
        <Route component={IndexPage} path="/index"></Route>
      </Switch>
    </Router>
  );
}

export default App;

3.子路由

在pages中建立sub資料夾,裡面建立Detail&list.js

import React, { Component } from 'react'

export default class detail extends Component {
    render() {
        return (
            <div>
                Detail Page
            </div>
        )
    }
}

import React, { Component } from 'react'

export default class list extends Component {
    render() {
        return (
            <div>
                list page
            </div>
        )
    }
}

index.js中

import React, { Component } from 'react'
import { Link } from 'react-router-dom'


export default class index extends Component {
    constructor(props){
        this.stata={}
        super(props)
    }
    render() {
        const {children} = this.props
        return (
            <div>
                <ul>
                    <li>
                        <Link to="/sub/list">列表頁</Link>
                    </li>
                    <li>
                        <Link to="/sub/detail">詳情頁</Link>
                    </li>
                </ul>
                {children}
            </div>
        )
    }
}

app.js中

import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom'
import { Route, Switch, NavLink, Link } from 'react-router-dom'
import IndexPage from './pages/index'
import LoginPage from './pages/login'

import DetailPage from './pages/sub/detail'
import ListPage from './pages/sub/list'
function App() {
  return (
    <Router>
      <Switch>
        <Route component={LoginPage} path="/login"></Route>
        <Route  path="/index" render={ props =>(
          <IndexPage>
            <Switch>
            <Route component={DetailPage} path="/sub/detail"></Route>
            <Route component={ListPage} path="/sub/list"></Route>
            </Switch>
          </IndexPage>
        )}/>
      </Switch>
    </Router>
  );
}

export default App;