egg.js Basics

This article addresses: https://www.cnblogs.com/veinyin/p/11944476.html

 

controller service

Naming Rules

File name lowercase

class name is the file name capitalized + Controller | Service camelCase

Example: controller folder to create a new file user.js

class UserController extends Controller

 

Asynchronous call

 If you need to use the service call async await 

If ejs rendering the page need to use async await 

 

Call the method

this.app.controller. filename method defined in the file name

this.service. filename method defined in the file name

Can pass parameters

Example call controller under user info in the method  

const res = await this.app.controller.user.info()

 

 

Routing parameter passing

Routing route.js defined -> Address bar input routing 

Take reference embodiment -> is the result parameter

 

get parameter passing

url -> url?a=1

this.ctx.query  -> { a: 1 }

 

url/:id  -> url/1

this.ctx.params -> { id: 1 }

 

post parameter passing 

this.ctx.request.body -> { a: 1, b: 2 }

 

put parameter passing

url/:id -> url/1

this.ctx.params -> { id: 1 }

 

delete parameter passing

url/:id -> url/1

this.ctx.params -> { id: 1 }

 

post request configuration 

Add in config / config.default.js file

const security = {
    csrf: {
        enable: false,
    },
};

 

Static resources

Place the directory app / public   must begin with / public  to avoid the path problem

Example using image resources

app/public/images/demo.jpg

<img src="/public/images/demo.jpg" />

 

 MySQL

Installation egg-mysql plug-reference document configuration database information

egg mysql automatic loading by using correlation methods in this.app.mysql app 

 

get [table name, query]

Example:

get ( 'table_name', {id: 1}) // query a data

 

INSERT [table name, Inserts]

Example: 

insert ( 'table_name', {a: 1, b: 2}) // insert data

 

select [table name, optional]

where query 

Items columns to query

Sorting order

limit offset related page

Example:

select ( 'table_name') // lookup table

select('table_name', {

  where: { id: 1 },

  columns: ['name', 'age', 'gender'],

  order: [ ['id', 'desc'] ],

  limit: 10,

  offset: 0,

});

 

update [table name, insert content, options]

Example:

update('table_name', { name: 'yyh' }, { where: { userId: 1 } })

If you insert the query with default ID is not set within the content to look at options to specify which keys

 

delete [table name, delete conditions]

Example: 

delete('table_name', { id: 1 })

 

query [Statement] 

Example:

query('select userName, userAge from table_name where id = ?', [1])

If you are using sql statement uses query

 

 

 END~~~≥ω≤

 

Guess you like

Origin www.cnblogs.com/veinyin/p/11944476.html