I built a front and back end project based on the current development framework of the project team, mainly realizing how to generate an interface on the node end and how to call the front-end project

Vue for the front end + Axios for the back end egg.js + Sequelize

1. The table

I use a list of their own casually written table simulation, although simulation, but also to add comments oh

CREATE TABLE `rank_list` (
        `id` INT(11) NOT NULL AUTO_INCREMENT,
        `name` VARCHAR(50) NOT NULL DEFAULT ' ' COMMENT 'Ranking content' COLLATE 'utf8mb4_general_ci',
        `created_at` INT(11) NOT NULL COMMENT 'Creation time, Unix timestamp, in seconds',
        `sort` INT(11) NOT NULL DEFAULT '0' COMMENT 'Ranking number'.PRIMARY KEY (`id`) USING BTREE,
        INDEX `created_at` (`created_at`) USING BTREE
)
COMMENT='Leaderboard'
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB
;
Copy the code

We can see that there is one in the local database

The next step is how do I read the data in this table

2. The node project

2.1 Creating a Node project -egg-example

Set up the initial project with egg.js

$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i

npm run dev
Copy the code

A node project has been set up, using the framework of Egg. Js, because ORM will be more than SQL, write SQL error prone, you can simply add, delete, modify and query using ORM, but copy summary, etc., can use SQL, SQL is more flexible for complex data relationship processing. Recommendation: Pros and cons of SQL versus ORM

2 Download the Sequelize ORm framework

npm install --save egg-sequelize mysql2 
Copy the code

Since using the plugins in egg.js has to be introduced manually, the egg-sequelize plug-in is included in the config/plugin.js file

'use strict'

/ * *@type Egg.EggPlugin */
module.exports = {
  // had enabled by egg
  // static: {
  // enable: true,
  // }
  sequelize: {
    enable: true.package: 'egg-sequelize',}}Copy the code
2.2 configure config

Create a new file under config, called config.local.js

The config. Local. Js

'use strict'

const nowMode = 'local'
const mysqlConfigMap = {
  local: {
    username: 'xxx'.password: 'xxx'.host: '127.0.0.1'.port: xxx,
  },
}

const dataBaseMap = {
  local: {
    database: 'test'.// It is the name of the database in your database. I have the screenshot of test above}},const mysqlBaseConfig = {
  dialect: 'mysql'. mysqlConfigMap[nowMode],timezone: '+ 08:00'.define: {
    freezeTableName: true.// Prevent changing table names to complex numbers
    underscored: true.// Prevent hump fields from being underlined by default}},module.exports = () = > {
  return {
    // Database configuration
    sequelize: {
      datasources: [{
        delegate: 'model'.baseDir: 'model'. dataBaseMap[nowMode], ... mysqlBaseConfig, }], }, } }Copy the code

How can you configure the sequelize search keyword config

Let’s look at how to use the ORM tool to read the data in the table

2.3 Writing data from the table to the Model

Create a rankList file with the same name as the table name. This Model can be accessed in the Controller and Service via app.model.XXX(XXX is the rank_list table) Sequelize searches for the keyword model

'use strict'
/* Leaderboard */
module.exports = app= > {
  const { INTEGER, STRING } = app.Sequelize

  const RankList = app.model.define('rank_list', {
    id: {
      type: INTEGER(11),
      primaryKey: true.autoIncrement: true.comment: 'primary key',},name: {
      type: STRING(50),
      allowNull: false.defaultValue: ' '.comment: 'Ranking content',},sort: {
      type: INTEGER(11),
      allowNull: false.defaultValue: 1.comment: 'Ranking number',},createdAt: {
      type: STRING(256),
      allowNull: false.defaultValue: ' '.field: 'created_at'.comment: 'Creation time',}})return RankList
}
Copy the code

2.4 Read the data in the table, write interface

1. Set routes

Find app/router.js ‘use strict’;

/ * * *@param {Egg.Application} app - egg application
 */
module.exports = app= > {
  const {
    router,
    controller: {
      home,
      rankList,
    },
  } = app
  router.get('/', home.index)
  router.get('/rankList', rankList.getRankingList)
}
Copy the code

GetRankingList refers to the g in the rankList file at the bottom of the controller file EtRankingList method

2. Create a rankList file under the Contorller file and call service data

'use strict'

const baseController = require('./baseController')

class RankListController extends baseController {
  async getRankingList() {
    const data = await this.service.rankList.getRankingList()
    this.success({ data })
  }
}

module.exports = RankListController
Copy the code

Since the success method that throws the interface data is available in the controller, you can create a baseController that is the same class as the rankList

BaseController File content

'use strict'

const { Controller } = require('egg')

class BaseController extends Controller {
  /** * public function that returns a successful result *@param { Object } Object Successful result data *@param { Number } Object.status HTTP status code *@param { Number } Object. Code Service code Status code *@param { String } Object. MSG Result information *@param { any } Object.data Indicates the returned data */
  success({ status = 200, code = 0, msg = 'success', data } = {}) {
    this.ctx.body = {
      code,
      msg,
      data,
    }
    this.ctx.status = status
  }
}

module.exports = BaseController
Copy the code

In general, the front end will judge code = 0 to indicate success and return the corresponding data format

RankList File contents

'use strict'

const baseController = require('./baseController')

class RankListController extends baseController {
  async getRankingList() {
    const data = await this.service.rankList.getRankingList()
    this.success({ data })
  }
}

module.exports = RankListController
Copy the code

Here RankListController no longer inherits from its parent class, Controller, but from baseController, which is the grandfather of RankListController.

Instead of fetching data directly from the table, the controller currently calls the Service and asks the service to fetch data from the table

3. Service to retrieve the data in the table

An egg. Js’s official website

To understand why there are services and controllers, look at the official documentation

The controller parses the user’s input and returns the appropriate result

Service is an abstraction layer used to encapsulate business logic in complex business scenarios, write SQL, or process data with ORM, and read data from tables

RankList contents under service

'use strict'

const Service = require('egg').Service

class rankListService extends Service {
  /** * Leaderboard */
  async getRankingList() {
    const { rows, count } = await this.ctx.model.RankList.findAndCountAll({
      attributes: { exclude: [ 'createdAt'.'updatedAt']}})return { list: rows, total: count }
  }
}

module.exports = rankListService
Copy the code

2.5 Read Data based on routes

3 Front end call interface data

3.1 Create a front-end VUE project with vue-CLI

Global installation

npm install -g @vue/cli
Copy the code

Create a project

vue create project
Copy the code

Go to the folder

cd project
Copy the code

run

npm run serve
Copy the code

Install axios first

npm install axios --save
Copy the code

Create request file and API file

Reference: VUe-CLI uses AXIos to simulate requesting interface data

The request content

import axios from 'axios'

var baseURL = 'http://127.0.0.1:7001'

const service = axios.create({
  baseURL: baseURL,
  timeout: 100000 // request timeout
})

service.interceptors.request.use(
  config= > {

    return config
  },
  error= > {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response= > {
    const res = response.data
    // console.log('resp:')
    // console.log(res)
    // if the custom code is not 0, it is judged as an error.
    if(res.code ! = =0) {
      alert('! = = 0 ')
      return Promise.reject(res.message || 'error')}else {
      return res.data
    }
  },
  error= > {
    console.log('err' + error) // for debug
    let msg = error.message
    console.log(msg);
    return Promise.reject(error)
  }
)

export default service
Copy the code

RankList API content

import request from '@/utils/request'

export function getRankList() {
  return request({
    url: '/rankList'.method: 'get'})},Copy the code
3.2 call

template

<div style="border-top: 1px solid red">
   <div v-for="(item, index) in rankList" :key="index">{{item.name}} {{item.name}}</div>
</div>
Copy the code

javascript

import { getRankList } from '@/api/rankList'
export default {
  name: 'HelloWorld'.data() {
    return {
      rankList: [].}},async created() {
    const { list } = await getRankList()
    this.rankList = list
    console.log(this.rankList, 'this.rankList')}}Copy the code
3.3 Display Effect

Cross-domain, this is where you set cross-domain on the server

1. Download egg-cors

 npm i egg-cors --save
Copy the code

2. Configure it in plugin

'use strict'

/ * *@type Egg.EggPlugin */

module.exports = {
  // had enabled by egg
  // static: {
  // enable: true,
  // }
  sequelize: {
    enable: true.package: 'egg-sequelize',},cors: {
    enable: true.package: 'egg-cors',}}Copy the code

3. Run

npm run dev
Copy the code

The final result

Welcome everyone to communicate, cherish every day, live a good moment – –