background

This article mainly shows the steps to build a project framework using Express and MySQL, showing how to build a project and perform basic operations.

Express

Create a project

Express is a fast, open and minimalist Web development framework based on node. js platform.

Install express-Generator globally

Express-generator is an Express application generator tool that you can use to quickly create application frameworks.

npm install -g express-generator

Create a project

Express expressFrame (expressFrame is the project name)

The directory structure of the project

Bin/WWW is a startup entry file, in which you can set port numbers, etc

Download the dependent

Once the project is created, it contains the basic project files as well as dependencies

npm install

Start the project

npm start

The start command can also be:

nodo ./bin/www

Install nodemon

Nodemon can be installed to monitor any changes to node.js source code and automatically restart your server

Install Nodemon globally:

npm install -g nodemon

Start the project

nodemon bin/www

That’s a good boot

Open your browser to http://localhost:3000 to see the page

Add a print log file

Winston logs are used here

Specific usage can see documents: www.npmjs.com/package/win…

Install Winston

npm i winston

Configure the print log format

Add a logger.js file (on Github) to the root of the project to configure the print log format.

Modify the app.js configuration

Change the project’s default variable name

Const logger = require(‘ Morgan ‘); To:

const morgan = require('morgan')

Use (logger(‘dev’)); To:

app.use(morgan('dev'));

Import the logger.js file

const logger = require('./logger')

Modify error handling

Print errors to a log

Test whether logs are printed successfully

Request a nonexistent routing, such as: http://localhost:3000/hello

Open the log file and see the error printed out

MySQL

Start the database

The method used here is to install MySQL with Docker

Here is the installation tutorial: www.runoob.com/docker/dock…

Install database management tools

Sequel Pro installed for macOS users

Navicat installation for Windows users

After Sequel Pro starts data, Sequel Pro connects to the database using the same password you set when you start the database

Creating a database

Use the database management tool to create a database. Name: expressFrame

Enter the expressFrame library and create a user information table as user. The default user information table has an ID field. Add the following necessary fields:

Field:id

Field:name Type:VARCHAR LENGTH:255 Comment: name

Field:phone Type:VARCHAR LENGTH:255 Comment: phone number

Use Knex to add, delete, and modify the database

Knex.js is a SQL query builder designed for Postgres, MSSQL, MySQL, MariaDB, SQLite3, Oracle and Amazon Redshift. It is flexible, portable and fun to use. Knex’s primary target environment is Node.js, you need to install the Knex library, and then install the appropriate database libraries: Pg works with PostgreSQL and Amazon Redshift, mysql works with mysql or MariaDB, sqlite3 works with SQlite3 or mysql works with MSSQL.

Download dependencies

npm install -save knex mysql

Adding Configuration Information

In the root directory of the project, create the config. Js configuration information. The subsequent configuration information involves the database and password, and cannot be uploaded to Github or other hosting platforms. Sensitive configuration information will be configured here. The host address is the service address of the database, and the local address is 127.0.0.1.

Const configs = {mysql: {host: '127.0.0.1', port: '3306', user: 'root', password: '123456', 'expressFrame' // database name}, // print error log: { error (message) { console.log('[knex error]', message) } } } module.exports = configsCopy the code
New. Gitignore

In the project root directory, create.gitignore to avoid uploading config.js, log, node_modules and other files that do not need to be uploaded to Github.

.ds_store.idea NPM -debug.log yarn-error.log node_modules log # config.js is a file I will not add here, I will upload it to GithubCopy the code
Database Configuration

Create models/knex.js and initialize knex

Const configs = require('.. /config'); Module. exports = require('knex')({client: 'mysql', connection: {host:}) // module. Exports = require('knex')({client: 'mysql', connection: {host: configs.mysql.host, port: configs.mysql.port, user: configs.mysql.user, password: configs.mysql.password, database: Configs.mysql. database}, // Error: {error (message) {console.log('[knex error]', message)}}})Copy the code
Knex add delete change check

Create a new file base.js under Models

const knex = require('.. /models/knex'); class Base{ constructor(props){ this.table = props; } all (){return knex(this.table).select(); } // add new insert(params) {return knex(this.table). } return knex(this.table). Where ('id', '=', id).update(params); } / / delete the delete (id) {return knex (enclosing table). The where (' id 'and' = ', id). Del (); } } module.exports = Base;Copy the code
Creating a User Model

Create a new file user.js under models

const Base = require('./base'); Class User extends Base {constructor(props = 'User '){super(props); } } module.exports = new User();Copy the code
Creating a User Controller

In the root directory, create the controllers folder, create user.js, and set the showUser method

Const User = require('.. /models/user.js'); Const userController = {// showUser gets user data and returns to the page showUser: Async function(req,res,next){try{let userData = await user.all () res.json({code: 200, message: "operation succeeded ", data: Json ({code: 0, message: "failed ", data: e})}},} module. Exports = userController;Copy the code
Added obtaining a user interface

Modify routes/index.js to add the interface for obtaining user information

const userController = require('.. /controllers/user'); Router. get('/get_user', userController.showuser);Copy the code

The test interface

Visit http://localhost:3000/get_user

View the data returned by the interface

That’s it

Github address: github.com/ysm27/expre…

Pass by and give me a thumbs up