1.安装node
2.安装mysql,配置环境变量
3.安装vsCode的mysql插件
1.创建项目
npm init -y
2.安装依赖
npm i express mysql
3.安装配置热更新
npm i hotnode -g // 安装
4.配置启动命令
"start": "hotnode index.js" // package.json中配置启动命令
const express = require("express");
const app = express();
// 请求拦截 会匹配所有请求
app.all("*", (req, res, next) => {
const login = Math.random();
if (login > 0.5) return res.json("未登录");
next();
});
// get请求
app.get("/", (req, res) => {
res.send("Hello World");
});
app.get("/liyfn", (req, res) => {
res.send("Hello liyfn");
});
// post
app.post("/post", (req, res) => {
res.json({ name: "liyfn" });
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
// 安装body-parser
const bodyParser = require("body-parser");
app.use(bodyParser.json()); // json请求
app.use(bodyParser.urlencoded({ extended: false })); // 表单
// 使用 body:请求体 query:查询参数
app.post("/post", (req, res) => {
console.log(req.query, req.params, req.body);
res.json({ name: "liyfn" });
});
// 解决跨域
const cors = require("cors");
app.use(cors());
1.基础连接
// 创建连接对象
var connection = mysql.createConnection(options);
// 连接
connection.connect(function(err) { *** });
// 关闭
connection.end(function(err) { *** });
connection.destroy();
2.连接池
// 连接mysql
const mysql = require("mysql");
const db = mysql.createPool({
host: "localhost",
user: "root",
port: "3306",
password: "123456",
database: "demo",
});
db.query("select * from userinfo", (err, data) => {
console.log(data);
});
3.区别
当连接不再需要时,这些连接可以缓存在连接池中,当接收到下一个客户端请求时,从连接池中取出连接并重新利用,而不需要再重新建立连接
yarn global add express express-generator
express --view=pug
--version 打印版本号
-e, --ejs 添加 ejs 引擎支持
--pug 添加 pug 引擎支持
--hbs 添加 handlebars 引擎支持
-H, --hogan 添加 hogan.js 引擎支持
-v, --view <engine> 添加 <engine> 视图引擎支持 (ejs|hbs|hjs|jade|pug|twig|vash) (默认为 jade)
-c, --css <engine> 添加 <engine> 样式表引擎支持 (less|stylus|compass|sass) (默认为纯 css)
--git 添加 .gitignore
-f, --force 对非空文件夹强制执行
-h, --help 打印帮助信息
1.安装winston
yarn add winston
2.封装本地日志写入方法logger.js
const { createLogger, format, transports } = require("winston");
const fs = require("fs");
const path = require("path");
const env = process.env.NODE_ENV || "development";
const logDir = "log";
// Create the log directory if it does not exist
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const filename = path.join(logDir, "results.log");
const logger = createLogger({
// change level if in dev environment versus production
level: env === "production" ? "info" : "debug",
format: format.combine(
format.label({ label: path.basename(process.mainModule.filename) }),
format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" })
),
transports: [
new transports.Console({
format: format.combine(
format.colorize(),
format.printf(
(info) =>
`${info.timestamp} ${info.level} [${info.label}]: ${info.message}`
)
),
}),
new transports.File({
filename,
format: format.combine(
format.printf(
(info) =>
`${info.timestamp} ${info.level} [${info.label}]: ${info.message}`
)
),
}),
],
});
module.exports = logger;
3.改写原错误处理方式
const logger = require("./logger");
const errorHandler = (err, req, res, next) => {
logger.error(`${err.method} ${req.originalUrl}` + err.message);
const errorMessage = err.message;
res.status(err.status || 500).json({
code: -1,
success: false,
message: errorMessage,
data: null,
});
};
app.use(errorHandler);
1.安装mysql插件 mysql 和 查询构建器knex
yarn add mysql knex
2.配置文件
module.exports = {
mysql: {
host: "127.0.0.1",
port: 3306,
user: "root",
password: "123456",
database: "demo",
},
log: {
error(msg) {
console.log("[knex error]", msg);
},
},
};
3.连接数据库 knex.js
const config = require("../config");
const knex = require("knex");
// 建立连接
module.exports = knex({
client: "mysql",
connection: {
...config.mysql,
},
log(msg) {
console.log("[knex error]", msg);
},
});
4.封装基础增删改查方法base.js
const knex = require("./knex");
// 增删改查
class Base {
constructor(table) {
this.table = table;
}
// 查
get() {
return knex(this.table).select();
}
// 增
insert(params) {
return knex(this.table).insert(params);
}
// 改
update(id, params) {
return knex(this.table).where("id", "=", id).update(params);
}
// 删除
del(id) {
return knex(this.table).where("id", "=", id).del();
}
}
module.exports = Base;
5.封装表模型
const Base = require("./base");
class Author extends Base {
constructor(props = "author") {
super(props);
}
}
module.exports = new Author();
6.数据查询
const Author = require("../models/author");
// 获取数据
const getAuthor = {
showUser: async (req, res) => {
try {
let data = await Author.all();
res.json({
code: 200,
message: "操作成功",
data,
});
} catch (error) {
res.json({
code: 0,
message: "获取失败",
});
}
},
};
module.exports = getAuthor;
7.接口返回封装
var express = require("express");
var router = express.Router();
const authorController = require("../controllers/author");
/* GET users listing. */
router.get("/", authorController.showUser);
module.exports = router;
https://knexjs.org/guide/