React + Koa2打造『官方管理后台』6

十六.数据请求、接口权限验证、登录验证中间件

1.在config中管理API

const BASE_URL = "http://localhost:3000";
const API ={
    LOGIN:{
        LOGIN_ACTION: BASE_URL+'/admin/login_action',
        LOGIN_CHECK:BASE_URL+'/admin/login_check',
        LOGOUT_ACTION:BASE_URL+'/admin/logout_action'
    },
    COURSE:{
        GET_COURSE_DATA:BASE_URL+'/get_courses'
    }
   
    
}

2.service中的login更改

import HTTP from '../utils/http';
import {API} from '../config/config';

const LOGIN = API.LOGIN

export default class LoginService extends HTTP{
    loginAction(userInfo){
        return new Promise((resolve,reject)=>{
            this.axiosPost({
                url:LOGIN.LOGIN_ACTION,
                data:userInfo,
                success(data){
                    resolve(data)
                },
                error(error){
                    alert('网络请求失败!');
                   
                }
            })
        })
    }...

3.后端写index.js的路由

const Router = require('koa-router')

const router = require('koa-router')(),
      indexController = require('../controller/index')
      router.get('/',indexController.index )      
      router.get('/get_courses',indexController.getCourseData)
      module.exports = router  

   

4.controller中书写方法,service中写对应方法

service

 async getCourses(){
        return await CourseModel.findAll()
    }

error_config

API:{
        RETURN_SUCCESS:{
            error_code:0,
            error_msg:'Data is returned successfully'
        },
        RETURN_FAILED:{
            error_code:20001,
            error_msg:'It is failed to return data'
        }
    }

controller

const {redisSet,redisGet}= require('../lib/redisClient') ;
const {getCourses} = require('../service/course');
const {API} = require('../config/err_config');
const {returnInfo} = require('../lib/util')
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
        }
    }
    async getCourseData(ctx,next){
        const data = await getCourses();
        ctx.body = data 
                 ? returnInfo(API.RETURN_SUCCESS,data)
                 : returnInfo(API.RETURN_FAILED)
    }
}
module.exports = new Index();

5.前端调用

service/course.js

import HTTP from '../utils/http'
import {API} from '../config/config'
const COURSE = API.COURSE
export default class CourseService extends HTTP {
   getCourseData(){
       return new Promise((resolve,reject)=>{
           this.axiosGet({
               url:COURSE.GET_COURSE_DATA,
               success(data){
                resolve(data)
                },
                error(error){
                    alert('网络请求失败!');
                
                }
           })
       })
   }
}

引入index

componentDidMount(){
        this.loginCheck();
        courseService.getCourseData().then((res)=>{
            console.log(res)
        })
    }

刷新测试报错

 async getCourses(){
        // return await CourseModel.findAll()
        return null
    }

6.后端指定查询数据

 async getCourses(){
        return await CourseModel.findAll({
            attributes:{
                exclude:['posterUrl','description','createAt','updateAt']
            }
        })
        
    }

7.前端处理返回数据

 courseService.getCourseData().then((res)=>{
            const errorCode = res.error_code;
            if(errorCode === 20001){
                alert('获取数据失败,清检查网路情况');
                return
            }
            const data = res.data
            console.log(data)
        })

8.接口请求中间件,检测是否登录

后台根目录下建立middlewares文件夹,loginCheck.js

const {returnInfo} = require('../lib/util'),
      {LOGIN} = require('../config/err_config');
module.exports = async(ctx,next)=>{
    if(ctx.session.userInfo){
        await next();
        return
    }
    ctx.body = returnInfo(LOGIN.NOT_LOGIN_STATUS)
}      

 

路由中

const router = require('koa-router')(),
      indexController = require('../controller/index'),
      loginCheck = require('../middlewares/logincheck')
      router.get('/',loginCheck,indexController.index )      
      router.get('/get_courses',loginCheck,indexController.getCourseData)
      module.exports = router  

   

前端的index中

componentDidMount(){
        this.loginCheck();
        courseService.getCourseData().then((res)=>{
            const errorCode = res.error_code;
            if(errorCode === 10006){
                const {history} = this.props;
                history.push('/login')
                return;
            }
            if(errorCode === 20001){
                alert('获取数据失败,清检查网路情况');
                return
            }
            const data = res.data
            console.log(data)
        })
    }

用接口软件测试

十七.修复数据表、爬虫接口权限验证

1.删除course/courseTab表

2.在course文件中删除field=-1,modules中增加field默认值为0

3.省略全部,crawler/courseTab

const Crawler = require('../lib/crawler'),
      {crawler} = require('../config/config');
 Crawler({
     url:crawler.url.course,
     callback(){
         const $ = window.$,
               $item = $('.course-tab-filter li');
         let data = [];
         $item.each((index,item)=>{
             const $el = $(item),
                   $itemLk = $el.find('.course-tab-filter-item'),
                   title=$itemLk.text().replace(/促/,'');
              if(title !== '全部'){
                const dataItem = {
                    cid:index,
                    title:$itemLk.text().replace(/促/,'')
                   
                  
                }     
                data.push(dataItem)   
              }     
            
         })  
         return data; 
     }
 })     

 

同步表/访问接口,给所有爬虫路由增加中间件

十八.配置表格、编写表格组件、提取公共组件

1.初始化

common.css

.list-container{
    height: 100%;
    padding: 20px;
}

2.在components下建立公共组件文件夹common,其中中编写ListTittle

import React, { Component } from 'react'
import './index.scss'
export default class ListTitle extends Component {
    render() {
        const {title,onRefreshData} = this.props;
        return (
            <div className="list-title">
                <h1 className="title">{title}</h1>
                <span
                    className = "refresh-btn"
                    onClick = {onRefreshData}
                >
                    <i className="iconfont">&#xe610;</i>
                    刷新数据</span>
            </div>
        )
    }
}

.list-title{
    height: 60px;
    border-bottom: 1px solid #ddd;
    line-height: 60px;
    .title{
        float: left;
    }
    .refresh-btn{
        float: right;
        cursor: pointer;
        color:#23b8ff;
        .icon-font{
            margin-right: 5px;
        }
    }
}

3.修正与传递

删除Index.js中的测试代码

app.js传递history

<Route component={ CoursePage } path="/course" history={props.history}></Route>

4.utils中的tools中编写没有数据跳转404的方法

function trimSpace(str){
    return str.replace(/\s+/g,'')
}
function getDatas(errorCode,data,history,callback){
    if(errorCode === 0 && data ){
        callback()
    } else{
        const {history} = this.props;
        history.push('/404')
    }
}
export{
    trimSpace,
    getDatas
}

5.config中新建table_config.js

const COURSE_TH=[
    '课程ID',
    '课程图片',
    '课程名称',
    '课程价格',
    '报名人数',
    '课程分类',
    '课程上下架'

];
export{
    COURSE_TH
}

6.common.css改为scss

.list-container{
    height: 100%;
    padding: 20px;
    .list-table{
        width: 100%;
        margin-top: 10px;
        tr{
            height: 60px;
            &:nth-child(odd){
                background-color: #efefef;
            }
            th{
                font-size: 16px;
            }
        }
    }
}

7.common中编写TableTh组件

import React, { Component } from 'react'
import './index.scss'
export default class TableTh extends Component {
    render() {
        const {thData} = this.props;
        return (
           <thead>
               <tr>
                   {
                       thData.map((item,index)=>{
                           return(
                               <th key={index}>{item}</th>
                           )
                       })
                   }
               </tr>
           </thead>
        )
    }
}

sub中的Course

import React, { Component } from 'react'

import {getDatas} from '../../../utils/tools';
import {COURSE_TH} from '../../../config/table_config';

import CourseService from '../../../services/course';

import ListTitle from '../../../components/common/ListTitle';
import TableTh from '../../../components/common/TableTh'

import './index.scss'

const courseService = new CourseService();

export default class Course extends Component {
    constructor(props){
        super(props);
        this.state={
            title:'课程管理',
            thData:COURSE_TH,

        }
    }
    onRefreshData(){
       
    }
    async getCourseData(){
        const result = await courseService.getCourseData(),
              errorCode = result.error_code,
              data = result.data,
              {history} = this.props;
              
              getDatas(errorCode,data,history,()=>{

                console.log(data);
                
              })
             
             
    }
    componentDidMount(){
        this.getCourseData()
    }
    render() {
        const {title,thData} = this.state;
        console.log(this.state);
        return (
            <div className="list-container">
               <ListTitle title={title}></ListTitle>
               <TableTh thData={thData} onRefreshData={this.getCourseData.bind(this)} ></TableTh>
            </div>
        )
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值