The introduction
Nodejs frameworks include Express, Koa, and Egg. What is the relationship between them?
The Express is the grandfather, the Koa is the son, and the Egg is the grandchild, so to speak, not in terms of their abilities, but in terms of their history.
Koa is a new Web framework, built by the same people behind Express, that aims to be a smaller, more expressive, and more robust cornerstone of web application and API development. By making use of async functions, Koa helps you discard callback functions and greatly enhances error handling. Koa does not bundle any middleware, but rather provides an elegant approach.
Based on ES6, ES7 and NodeJS, it is a Node.js Web framework with “convention over Configuration”. Egg follows the principle of “convention over Configuration” and develops applications according to a unified set of conventions. Adopting this approach internally reduces learning costs for developers, who are no longer “nails” and can be mobile. In a team without an agreement, the cost of communication is very high. For example, some people will divide functions by category while others will divide functions by category. It is easy for developers to make mistakes if their cognition is inconsistent. But conventions are not the same as poor extensibility; instead, Egg is highly extensible and can be customized to the team’s conventions. Using the Loader allows the framework to define default configurations for different environments, and you can override the default conventions of the Egg.
I think you understand the relationship by now, but what’s the difference between them?
In a word: KOA, Express, are low-level, attitudinal Web frameworks; Egg.js is based on KOA to do a good layer of framework packaging for large enterprise applications, small and medium-sized projects recommended egg.js, easy to use, easy to understand the concept.
In this case, we don’t need to worry about that much, but directly use the most native Express framework +Sequelize Mysql database link.
Installation environment
Install phpStudy, which integrates Apache, Nginx, MySql, Ftp, etc
The local database management tools, you can download, some links can be ignored: pan.baidu.com/s/15VSP0lgU… Extraction code: 4hHz
Support link database types are very many, free, free, free.
(1) After the installation, connect to the database
(2) Double-click the connection and right-click the connection name to create a new database
(3) After the library is built, you can click on the aboveThe new table
(4) When creating a table, click Add field, each table needs to add a primary key, you can select the following by defaultSince the increase
, so that no data inserted, it will automatically grow, without human intervention
(4) Automatic time,create_time
Is that the insertion time is recorded for each insertion,update_time
Yes The update time is recorded every time data is updated. Remember the difference in Settings.
Ok, now that I have my first table, start lifting time
Express builds a Web service
1. Create a package.json file under the local project
{
"name": "node-orm"."version": "1.0.0"."description": ""."author": "javan(www.javanx.cn)"."private": true."scripts": {
"dev": "cross-env NODE_ENV=development nodemon index.js --watch ./"."start": "cross-env NODE_ENV=production node index.js"}}Copy the code
2. Install the plug-in
npm install express sequelize mysql2 cross-env --save
Copy the code
npm install nodemon --save-dev
Copy the code
3. Create index.js in the root directory
const express = require('express')
const app = express()
// Define port 8111
app.listen('8111'.function () {
console.log("The server is running at *: 8111");
});
Copy the code
4. Start the service
npm run dev
Copy the code
Print “The server is running at *: 8111 The service has started. Open a browser and type http://localhost:8111/
The service is fine, then connect the data
Sequelize Connects to the database
1. Create a config directory to store some configuration js of the project, and then create config/db.js
/** * mysql database configuration */
// Build the environment
let sqlConfig = {
host: 'localhost'.user: 'root'.password: 'root'.database: 'test'.port: 3306
}
// Local environment
// process.env.node_env depends on the configuration in package.json
if(process.env.NODE_ENV ! = ='production'){
sqlConfig = {
host: 'localhost'.user: 'root'.password: 'root'.database: 'test'.port: 3306
};
}
module.exports = sqlConfig
Copy the code
Create a DB directory to store the database model and Sequelize configuration
Now the project catalog
3. Configure db/sequelize.js
var Sequelize = require('sequelize')
// Import the database configuration
var db = require('.. /config/db')
var sequelize = new Sequelize(db.database, db.user, db.password, {
logging: function(sql) {
// Logger is the logger instance of log4js
if(process.env.NODE_ENV ! = ='production') {console.log(sql)
}
},
port:db.port,
host: db.host,
dialect: 'mysql'.dialectOptions: {
dateStrings: true.typeCast: true
},
pool: {
max: 20.min: 1.acquire: 60000.idle: 10000
},
timezone: '+ 08:00' // Time zone 8 EAST
});
exports.sequelize = sequelize;
exports.defineModel = function (name, attributes) {
var attrs = {};
for (let key in attributes) {
let value = attributes[key];
if (typeof value === 'object' && value['type']) {
value.allowNull = value.allowNull || false;
attrs[key] = value;
} else {
attrs[key] = {
type: value,
// allowNull: false
};
}
}
attrs.version = {
type: Sequelize.BIGINT,
// allowNull: false
};
attrs.createUser = {
type: Sequelize.STRING,
allowNull: false
};
attrs.updateUser = {
type: Sequelize.STRING,
allowNull: false
};
return sequelize.define(name, attrs, {
tableName: name,
timestamps: true.paranoid: true.charset: 'utf8mb4'.collate: 'utf8mb4_general_ci'.hooks: {
beforeBulkCreate: function(obj){
obj.version = 0 ;
},
beforeValidate: function(obj){
if(obj.isNewRecord){
console.log('first');
obj.version = 0 ;
}else{
console.log('not first');
obj.version = obj.version + 1; }}}}); };Copy the code
4, db/model/user.js configuration, where the field and database corresponding
/**
* 用户
*/
var Sequelize = require('sequelize');
var {sequelize} = require('.. /sequelize.js');
var user = sequelize.define('user', {id: {
type: Sequelize.BIGINT(20),
primaryKey: true.allowNull: false.unique: true.autoIncrement: true
},
name: Sequelize.STRING(255), / / name
age: Sequelize.BIGINT(11), / / age
sex: Sequelize.BIGINT(1), / / gender
create_time: Sequelize.DATE,
update_time: Sequelize.DATE
},{
timestamps: false.SequelizeDatabaseError: Unknown column 'createdAt' in 'field list' SequelizeDatabaseError: Unknown column 'createdAt' in 'field list'
freezeTableName: true
});
module.exports = user;
Copy the code
Sequelize Mapping between data types and database types
Sequelize.STRING // VARCHAR(255)
Sequelize.STRING(1234) // VARCHAR(1234)
Sequelize.STRING.BINARY // VARCHAR BINARY
Sequelize.TEXT // TEXT
Sequelize.TEXT('tiny') // TINYTEXT
Sequelize.INTEGER // INTEGER
Sequelize.BIGINT // BIGINT
Sequelize.BIGINT(11) // BIGINT(11)
Sequelize.FLOAT // FLOAT
Sequelize.FLOAT(11) // FLOAT(11)
Sequelize.FLOAT(11.12) / / FLOAT (11, 12)
Sequelize.REAL // REAL is PostgreSQL only.
Sequelize.REAL(11) // REAL(11) is PostgreSQL only.
Sequelize.REAL(11.12) // REAL(11,12) is PostgreSQL only.
Sequelize.DOUBLE // DOUBLE
Sequelize.DOUBLE(11) // DOUBLE(11)
Sequelize.DOUBLE(11.12) / / DOUBLE (11, 12)
Sequelize.DECIMAL // DECIMAL
Sequelize.DECIMAL(10.2) / / a DECIMAL (1, 2)
Sequelize.DATE // DATETIME against mysql/sqLite, TIMESTAMP WITH TIME ZONE against postgres
Sequelize.DATE(6) // DATETIME(6) for mysql 5.6.4+. Decimal seconds support up to 6 bits of accuracy
Sequelize.DATEONLY // DATE does not contain time.
Sequelize.BOOLEAN // TINYINT(1)
Sequelize.ENUM('value 1'.'value 2') // An ENUM with "value 1" and "value 2" is allowed
Sequelize.ARRAY(Sequelize.TEXT) // Define an array. PostgreSQL only.
Sequelize.ARRAY(Sequelize.ENUM) // Define an ENUM array. PostgreSQL only.
Sequelize.JSON // JSON 列. 仅限于 PostgreSQL, SQLite and MySQL.
Sequelize.UUID // the UUID data type for PostgreSQL and SQLite, CHAR(36) BINARY for MySQL (default: Sequelize.UUIDV1 or sequelize. UUIDV4 for Sequelize to automatically generate ids)
Sequelize.GEOMETRY PostgreSQL (with PostGIS) or MySQL only.
Sequelize.GEOMETRY('POINT') // Spatial columns with geometric types. Only PostgreSQL (with PostGIS) or MySQL.
Sequelize.GEOMETRY('POINT'.4326) // Spatial column with geometry type and SRID. Only PostgreSQL (with PostGIS) or MySQL.
Copy the code
Index. js import db/model/user.js test wave
.const user = require('./db/model/user')
user.findAll().then(data= >{
console.log(data)
})
...
Copy the code
Print the SQL executed, and the result. Since we did not insert data into the new database, print an empty array. []
Let’s go to the database and create a new data, everybody watch out we just fill in the name, gender and age, id and time will be automatically inserted
After a query, directly modify index.js, save the program automatically hot update
The data query is back, and that’s the end of this section. I hope you all learned something.
Front end play Back End