当前位置:网站首页>Eggjs create application knowledge points
Eggjs create application knowledge points
2022-07-29 08:24:00 【Bean bag 3D world】
establish egg application
install egg
npm init egg --type=simple
Entry projectcd myegg
Installation dependencynpm install
Start the applicationnpm run dev
install egg-mongoose
npm install egg-mongoose --save
config Folder modification config.default.js
// Configure Links mongodb Path parameter
config.mongoose = {
client: {
url: 'mongodb://123:[email protected]/dcw',
options: {
},
},
};
Need to be revised plugin.js
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
// Enable mongodb
mongoose: {
enable: true,
package: 'egg-mongoose',
},
// keys: 'dcw',
};
establish controle server modle router
controller folders creating user.js
'use strict';
// from egg take controller example
const Controller = require('egg').Controller;
class UserController extends Controller {
async getUserList() {
const {
ctx, service } = this;
// obtain service Business logic data
const mockList = await service.user.find();
ctx.body = {
code: 1,
msg: 'success',
data: mockList,
};
}
}
module.exports = UserController;
service folders creating user.js
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async find() {
// Get the query data from the database model
const mockList = await this.ctx.model.User.find({
}, (d, s) => {
// console.log(d, s);
});
return Object.assign({
}, {
pageNum: 1,
pageSize: 10,
list: mockList,
});
}
}
module.exports = UserService;
model folders creating user.js
'use strict';
module.exports = app => {
// establish mongoose example establish Ausers surface
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
// Create table fields and types
const UserSchema = new Schema({
userName: {
type: String },
passWord: {
type: String },
});
const User = mongoose.model('Ausers', UserSchema);
return User;
};
Local development
Need to put egg-bin Module as devDependencies introduce
npm i egg-bin --save-dev
Start the application
add to npm scripts To package.json
{
"scripts": {
"dev": "egg-bin dev"
}
}
Can pass npm run dev Command to start the application
Environment configuration
Locally launched applications are based on env: local Starting up , The read configuration is also config.default.js and config.local.js The result of the merger
config To configure
egg Provide 5 Configuration files :
- config.default.js: Default profile ;
- config.local.js: Configuration in development environment , Merge with default configuration , The same name overrides the default configuration ;
- config.prod.js: Configuration in production environment , Merge with default configuration , The same name overrides the default configuration ;
- config.test.js: Configuration in test environment , Merge with default configuration , The same name overrides the default configuration ;
- config.unittest.js: Configuration in unit test environment , Merge with default configuration , The same name overrides the default configuration ;
Designated port
Start the application locally and listen by default 7001 port , Other ports can be specified , for example :
{
"scripts": {
"dev": "egg-bin dev --port 7002"
}
}
router Create knowledge points
router.resources(‘users’, ‘/api/users’, controller.users) The benefits are equivalent to defining a set RESTful The routing : As below 7 Routes
router.get("/api/users", controller.users.index);
router.get("/api/users/new", controller.users.new);
router.get("/api/users/:id", controller.users.show);
router.get("/api/users/:id/edit", controller.users.edit);
router.post("/api/users", controller.users.create);
router.put("/api/users/:id", controller.users.update);
router.delete("/api/users/:id", controller.users.destroy);
middleware (Middleware) Onion model

Write two test middleware middleware1 and middleware2
// middleware/middleware1.js
module.exports = (options, app) => {
return async function middleware1(ctx, next) {
console.log("==request one==");
await next();
console.log("==response one==");
}
};
// middleware/middleware2.js
module.exports = (options, app) => {
return async function middleware2(ctx, next) {
console.log("==request two==");
await next();
console.log("==response two==");
}
};
options: Middleware parameters , Can be found in Config Middle configuration ;
app and ctx It's also said above , These two objects can do many things in middleware , For example, you can get ctx.request Modify parameters, etc ;
next For a function , Next, we will talk about the function .
After writing the middleware, you need to config.default.js To configure :
// config/config.default.js
exports.middleware = ['middleware1', 'middleware2']; // The order of array is the order of middleware execution
exports.middleware1 = {
// Middleware parameters ( namely options)
msg: "extra message"
}
Expand (Extend) Folder

Many objects of the framework support extension , We can extend custom properties and methods on many objects , Extensible objects are :Application、Context、helper、Request and Response.
The way to write extensions is to create corresponding files , Then the object will be merged with the original object prototype On , This realizes the extended function , stay extend Create extension under folder application.js application.prod.js Why? application There will be 2 An extension file ? You can guess when you see the name , actually egg It also supports expansion according to the environment , So we can expand the required functions in a specific environment .
journal

stay Controller、Service When using logs in , Can be used directly ,this.logger, Yes none,warn,info,debug,error Other methods . The default directory is under the project logs, Its structure is :demo/logs/demo/…, Default to eggjs The first log is followed by the log generator . The log generation path and size can be in demo/app/config/config.${env}.js To configure , The configuration is as follows :
exports.logger = {
dir:'',// Configure log generation path
level:'DEBUG',// The level of logging
//.... Other
}
Timing publisher
The folder where the scheduled task is located :/app/schedule
const Subscription = require('egg').Subscription;
class schedule1 extends Subscription{
// Set scheduled task information
static get schedule(){
return {
interval:'1m',// Set the time interval
type:'all'// all worker All implemented
}
}
// What to do
async subscirbe(){
this.logger.info(123);
}
}
Cookie
adopt ctx.cookies, We can do it in controller Medium convenient 、 Secure settings and reads Cookie
class UserController extends Controller {
async add() {
const ctx = this.ctx;
let count = ctx.cookies.get('count');
count = count ? Number(count) : 0;
ctx.cookies.set('count', ++count);
ctx.body = count;
}
async remove() {
const ctx = this.ctx;
ctx.cookies.set('count', null);
ctx.status = 204;
}
}
ctx.cookies.set(key, value, options)
Set up Cookie It's actually through HTTP Set... In response set-cookie Head finished , every last set-cookie Will make the browser in Cookie A key value pair is stored in . Set up Cookie When it's worth it , The protocol also supports many parameters to configure this Cookie The transmission of 、 Storage and permissions
{Number} maxAge: Set the maximum save time of this key value pair in the browser . Is the number of milliseconds from the current time of the server
{Date} expires: Set the expiration time of this key value pair , If set maxAge,expires Will be covered . If maxAge and expires No settings ,Cookie Will fail in browser session ( Usually when the browser is closed ) It doesn't work
{String} path: Set the key value for the effective URL route , The default setting is on the root path (/), That is all under the current domain name URL You can visit this Cookie
{String} domain: Set the valid domain name of the key value pair , No configuration by default , It can be configured to be accessible only in the specified domain name
{Boolean} httpOnly: Set whether key value pairs can be js visit , The default is true, It is not allowed to be js visit
{Boolean} secure: Set key value pairs only in HTTPS Connect to transmit , The framework will help us to determine if we are currently HTTPS Connect to automatic settings secure Value
{Boolean} overwrite: Set up key How to deal with the same key value pair , If set to true, Then the value set later will override the value set earlier , Otherwise two set-cookie Response head
{Boolean} signed: Whether the setting is right Cookie To sign , If set to true, When the key value pair is set, the value of the key value pair will be signed at the same time , Check when you pick it up later , It can prevent the front end from tampering with this value . The default is true
{Boolean} encrypt: Whether the setting is right Cookie To encrypt , If set to true, It's sending Cookie The value of this key value pair will be encrypted before , The client could not read Cookie The plaintext value of . The default is false
// Sample settings
ctx.cookies.set(key, value, {
httpOnly: false,
signed: false,
});
// Get samples
ctx.cookies.get(key, options)
Cookie Secret key
Because we are Cookie Encryption, decryption and signature verification are needed in , So you need to configure a secret key for encryption . stay config/config.default.js in
module.exports = {
keys: 'key1,key2',
};
keys Configure as a string , You can configure multiple..., separated by commas key.Cookie When using this configuration for encryption and decryption :
Only the first key is used for encryption and signing .
Decryption and signature verification will traverse keys To decrypt .
If we want to update Cookie The secret key to , But I don't want to set it to the user's browser Cookie invalid , The new key can be configured to keys front , Wait a while and then delete the unnecessary secret key .
Session
Frame built in Session plug-in unit , It provides us with ctx.session To access or modify the current user Session
class UserController extends Controller {
async getPosts() {
const ctx = this.ctx;
// obtain Session Content on
const userId = ctx.session.userId;
const posts = await ctx.service.post.fetch(userId);
// modify Session Value
ctx.session.visited = ctx.session.visited ? (ctx.session.visited + 1) : 1;
ctx.body = {
success: true,
posts,
};
}
}
modify session, If you want to delete it , Assign it directly to null
// Set up
ctx.session.user ='xiaodoubao'
// Delete
ctx.session = null;
Set up session matters needing attention
Do not use _ start
Not for isNew
// Wrong usage
ctx.session._visited = 1; // --> This field will be lost on the next request
ctx.session.isNew = 'HeHe'; // --> For internal keywords , Should not change
For more information, please go to Xiaodou Bao 》
Scan the code and follow the official account of xiaodoubao

边栏推荐
- The first week of postgraduate freshman training: deep learning and pytorch Foundation
- What is the working principle of the noise sensor?
- Reading papers on false news detection (4): a novel self-learning semi supervised deep learning network to detect fake news on
- Personal study notes
- Detailed steps of installing MySQL 5.7 for windows
- Phy6252 is an ultra-low power Bluetooth wireless communication chip for the Internet of things
- ROS tutorial (Xavier)
- 数仓分层设计及数据同步问题,,220728,,,,
- Huawei wireless device configuration uses WDS technology to deploy WLAN services
- Random lottery turntable wechat applet project source code
猜你喜欢

MySQL中的时间函数

Unity shader learning (VI) achieving radar scanning effect

Day4: the establishment of MySQL database and its simplicity and practicality

Time function in MySQL

Windows 安装 MySQL 5.7详细步骤

Gan: generate adversarial networks

Inclination sensor accuracy calibration test

华为无线设备配置利用WDS技术部署WLAN业务

Centos7/8 command line installation Oracle11g

Smart energy management system solution
随机推荐
Inclination monitoring solution of Internet of things
DAC0832 waveform generator based on 51 single chip microcomputer
Nrf52832-qfaa Bluetooth wireless chip
RPC and rest
Tb6600+stm32f407 test
Component transfer participation lifecycle
Simplefoc+platformio stepping on the path of the pit
AES 双向加密解密工具
Privacy is more secure in the era of digital RMB
Arduino uno error analysis avrdude: stk500_ recv(): programmer is not responding
STM32 MDK (keil5) contents mismatch error summary
Unity多人联机框架Mirro学习记录(一)
PostgreSQL manually creates hikaridatasource to solve the error cannot commit when autocommit is enabled
Qt/pyqt window type and window flag
Collation of ml.net related resources
简易计算器微信小程序项目源码
ROS tutorial (Xavier)
Simplefoc parameter adjustment 1-torque control
Stm8s003 domestic substitute for dp32g003 32-bit microcontroller chip
Cs5340 domestic alternative dp5340 multi bit audio a/d converter