This article is based on the completed development process from the perspective of example, step by step to build an out-of-the-box Egg. Js application, let’s get started!
Full project address: gitee.com/koukaile/eg…
Table of contents for this series
- Egg enterprise actual combat (I) – frame building
- Egg enterprise actual combat (2) – login module
- Egg enterprise combat (3) – database
01. Install an egg. Js
Environment to prepare
Operating system: macOS, Linux, and Windows Operating environment: LTS version is recommended. The minimum requirement is 8.x.
Fast initialization
We recommend going straight to the scaffold and quickly generating the project with a few simple instructions (NPM >=6.1.0) :
$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
Copy the code
Start-up project:
$ npm run dev
$ open http://localhost:7001
Copy the code
02. Directory build
Here is a brief architectural presentation of the project
An egg - project ├ ─ ─ package. Json ├ ─ ─ app. Js (for custom startup initialization) ├ ─ ─ agent. The js (for custom startup initialization) ├ ─ ─ app | ├ ─ ─ the router, js (used to configure the URL Routing rules) | ├ ─ ─ contract (used to configure swagger) │ ├ ─ ─ the js (default interface type configuration) │ ├ ─ ─ contract. Js (request sample data configuration) │ ├ ─ ─ controller (used to resolve user input, Return the corresponding results after processing) │ | └ ─ ─ home. Js │ ├ ─ ─ service (for writing business logic layer) │ | └ ─ ─ the user. The js │ ├ ─ ─ middleware (for writing middleware) │ | └ ─ ─ Response_time. Js │ ├ ─ ─ the schedule (for timing task) │ | └ ─ ─ my_task. Js │ ├ ─ ─ public static resources (placed) │ | └ ─ ─ reset. CSS │ ├ ─ ─ the view (used to place template files, Prescribed by template plug-ins) │ | └ ─ ─ home. TPL │ ├ ─ ─ model (used to place the domain model, by field or related plug-in convention) │ └ ─ ─ the extend (for the expansion of the framework) │ ├ ─ ─ helper. Js (optional) │ ├ ─ ─ request. Js (optional) │ ├ ─ ─ the response. The js (optional) │ ├ ─ ─ the context, js (optional) │ ├ ─ ─ application. Js (optional) │ └ ─ ─ agent. The js (optional) ├ ─ ─ logs () is used to store log files ├ ─ ─ Config (used to write configuration files) | ├ ─ ─ the plugin, js (used in configuration needs to be loaded plug-ins) | ├ ─ ─ config. The default. The js │ ├ ─ ─ config. Production. The js | ├ ─ ─ config. Test. Js | ├ ─ ─ config. Local. Js | └ ─ ─ config. Preview the js └ ─ ─ test (for a unit test) | ├ ─ ─ middleware | | └ ─ ─ response_time. Test. The js | └ ─ ─ The controller | └ ─ ─ home. Test. Js └ ─ ─ the database (sequelize database)Copy the code
03. Database connection
Building a database
- Starting the database
- Building the database (this article uses PHPStudy)
- Connecting to a database (Navicat for this article)
Configure the database in egg
1. Install the corresponding plug-in egg-mysql:
$ npm i --save egg-mysql
Copy the code
2. Enable plug-in:
// address -> config/plugin.js exports.mysql = {enable: true, package: 'egg-mysql',};Copy the code
3. Single data source
If our application only needs to access one MySQL database instance, we can configure it as follows:
/ / address - > / config/config. The default. Js/config/database configuration. The mysql = {/ / single database information configuration client: {/ / host host: 'localhost', // port number: '3306', // username: 'user: ', // password: ', // database name: ",}, // Whether to load to app, app is enabled by default: true, // Whether to load to agent, agent is disabled by default: false,};Copy the code
4. Swagger Interface document configuration
Official use document: www.npmjs.com/package/egg…
To install an egg – swagger – doc
NPM I egg-swagger-doc --save // Automatically generate interface description configurationCopy the code
Configure an egg – swagger – doc
// address -> config/config.default.js exports.swaggerDoc = {dirScanner: './app/controller', // configure automatic scan controller path // interface document title, description or other apiInfo: {title: 'Render', // interface document title description: 'swagger- UI for Render document.', // schemes: [' HTTP ', 'HTTPS '], // Configure the supported protocol Consumes: ['application/json'], // specifies the content-type that processes the request, e.g. application/json, text/ HTML/produces: ['application/json'], // specifies the content type to return. SecurityDefinitions are returned only if the (Accept) type in the request header contains this type. { // type: 'apiKey', // name: 'clientkey', // in: 'header', // }, // oauth2: { // type: 'oauth2', // tokenUrl: 'http://petstore.swagger.io/oauth/dialog', // flow: 'password', // scopes: { // 'write:access_token': 'write access_token', // 'read:access_token': 'read access_token', // }, // }, }, enableSecurity: EnableValidate: true enableValidate: true enableValidate: true routerMap: True, // Whether to enable automatic route generation. The default is true. Enable: true, // The default is true.Copy the code
Configuration swagger
/ / address - > config/plugin. Js / / configure an egg - swagger - doc plug-in information module. Exports. Swaggerdoc = {enable: Swagger-ui: 'egg-swagger-doc', // specify the name of the third-party plug-in package};Copy the code
Create the business logic layer
config/plugin.js app/service/home.js const { Service } = require('egg'); // Get the Service base class of the egg objectCopy the code
All the business logic is set up in the business layer, in the control layer just call the corresponding method
'use strict' const Service = require('egg').Service; Class HomeService extends Service{// test data async test(){const result = await this.app.mysql.query('select * from test', '') return JSON.stringify({ code:1, message:'success', data:result }) } } module.exports = HomeServiceCopy the code
Creating a Controller (API)
// address -> app/controller/home.js const {controller} = require('egg'); // Deconstruct the Controller base classCopy the code
app/controller/home.js
'use strict' /** * @Controller **/ const Controller = require('egg').Controller; Class HomeController extends Controller {async Test () {/** * @summary Extends Database connection * @Description test Swagger * @Router Post /home/test * @request body String test Configuration request Sample data * @request header String Token EG: Write your params at here * @response 200 JsonResult */ const {CTX} = this; ctx.body = await this.service.home.test() } } module.exports = HomeController;Copy the code
Example data when configuring interface requests
// module. Exports = {//test test: {name: {type: 'string', required: true, enum: 'test' }, }, };Copy the code
Configure constraints on interface return values (must be configured)
// exports = {// default interface type JsonResult: {//@response 200 JsonResult result: {type: 'Boolean'}, // result: {type: 'Boolean'}, // result: {type: 'Boolean'} // The data returned by the server},}Copy the code
Configure router.js
// Address -> app/router.js 'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; // Redirect to swagger router. Redirect ('/', '/swagger-ui.html', 302); Get ('/home/test', controller.home.test); };Copy the code
Test the swagger
Enter http://127.0.0.1:7001/ in your browser
As shown in the picture above, you are done
05. Cross-domain issues
Cross-domain is the most common problem when the front and back ends are separated and interconnected, and the egg processing is handled cross-domain here
1. Download the Egg-cors package
npm i egg-cors --save
Copy the code
2. Enable CORS in plugin.js
exports.cors = {
enable: true,
package: 'egg-cors',
};
Copy the code
3. Set the parameters in config.default.js
Security = {CSRF: {enable: false, ignoreJSON: true,}, domainWhiteList: ['http://127.0.0.1'],}; config.cors = { origin: '*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', };Copy the code
06. Configure log printing
Log Configuration
// /config/config.local.js 'use strict'; module.exports = () => { const config = exports = {}; config.logger = { dir: '.. /logs/local', // print directory redirection outputJSON: true, // outputJSON format}; return { ... config, }; };Copy the code
Log type
First, there are three types of eggJS logs.
- Business log
common-error.log
egg-agent.log
egg-web.log
${appInfo.name}-web.log
- Scheduled Task Logs
egg-schedule.log
- Framework startup log
master-stderr.log
master-stdout.log
- Log print
logger.debug()
logger.info()
logger.warn()
logger.error()
07. Environment configuration
The complete life cycle of a project usually includes:
- The local environment
- The test environment
- Quasi-production environment (grayscale environment)
- Production Environment (online environment)
Configuration in egg (package.json)
"scripts": { "start": "egg-scripts start --daemon --title=egg-server-EggZoneFrame", "stop": "Egg-scripts stop --title= egg-server-eggzoneFrame ", "dev": "egg-bin dev --env=local",// local environment "dev-test": "Egg -bin dev --env=test", "dev-preview": "egg-bin dev --env=preview", "dev-production": "Egg -bin dev --env=production", "egg-bin dev ", "test": "npm run lint -- --fix && npm run test-local", "cov": "egg-bin cov", "lint": "eslint .", "ci": "npm run lint && npm run cov", "autod": "autod" },Copy the code
–env= Environment name Configures the current environment
NPM Run Environment parameter to start the corresponding environment, NPM run dev // Start the local environment. NPM run dev-test // Start the test environment. NPM run dev-preview // Start the production environment // Start production environmentCopy the code
The config configuration
Generally, different environments need to configure different database addresses, port addresses, log printing directories, etc.
- Config.default. js Specifies the default configuration
- Config.local. js Configures the local environment
- Config.test. js Configures the test environment
- Config.preview.js Pre-production environment configuration
- Config.production. js Configures the production environment
08. Summary
At this point, a set of Node services has been set up
Summary:
- The installation
- Building the development catalog
- Database connection
- Configuration swagger
- Cross-domain before and after processing
- Log Configuration
- Environment configuration
If all above are set up, then the Node framework is set up successfully. Go to your front end interface to connect to it. If you like it, give it a thumbs up