04-Express connect to mysql database

04-Express connect to mysql database

1.Express generated directory

The premise is that express is installed globally
npm i express -g
express 项目名称

2. Install mysql

npm install mysql

Create a new Model.js in the new model directory model in the project root directory to write the base class of mysql

const mysql = require('mysql')
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'root',  // 注意修改为你自己的数据库密码
  port: '3306',
  database: 'newsdatabase'  // 注意修改为你自己的数据库密码
})
/* 封装一个数据库模型基类 */
module.exports = class Model {
  /**
   * 描述:执行sql 语句的方法
   * @param {*} sql  要执行的 sql 语句
   * @param {*} params 给sql 语句占位符进行赋值的参数 数组
   * @returns
   */
  static query(sql, params) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => {
        if (err) {
          connection.release()
        } else {
          connection.query(sql, params, (err, result) => {
            if (err) {
              reject(err)
            } else {
              resolve(result)
            }
            // 结束会话,释放连接
            connection.release()
          })
        }
      })
    })
  }
}

Create a new AuthModel.js under the model (this name is arbitrary)

module.exports = class AuthModel extends require('./Model') {
  /**
   * 描述:查询用户列表数据
   * @returns 返回用户列表数据
   */
  static findUserList() {
    return new Promise((resolve, reject) => {
      let sql = 'select * from info_user'
      this.query(sql)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
}

Create a new dao directory under the project root directory, and create a new AuthDao.js under the dao directory

module.exports = class AuthDao extends require('../model/AuthModel') {
  /**
   * 描述:查询用户数据列表
   * @param {*} req
   * @param {*} res
   */
  static async findUserDao(req, res) {
    const result = await this.findUserList()
    console.log(result)
    res.send(result)
  }
}

Modify in routes/users.js

var express = require('express')
var router = express.Router()
const AuthDao = require('../dao/AuthDao')
// 验证数据库的接口
router.get('/', (req, res) => {
  AuthDao.findUserDao(req, res)
})
module.exports = router

Add cross-domain code in app.js

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
//设置跨域访问
app.all('*', function (req, res, next) {
  // 设置请求头为允许跨域
  res.header('Access-Control-Allow-Origin', '*')
  // res.header('Access-Control-Allow-Origin', '*')
  // 设置服务器支持的所有头信息字段
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild, sessionToken'
  )
  // 设置服务器支持的所有跨域请求的方法
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
  res.header('Access-Control-Allow-Credentials', true)
  if (req.method.toLowerCase() == 'options') {
    res.send(200) // 让options尝试请求快速结束
  } else {
    next()
  }
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Test, start the project npm start
connect to the database successfully, and successfully return data

Insert picture description here