本文主要是学习koa的使用。
pnpm init
pnpm install koa koa-router mysql2
USE notes_app;
DROP TABLE IF EXISTS `notes_categories`;
CREATE TABLE IF NOT EXISTS notes_categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255),
puid VARCHAR(32) NOT NULL
);
INSERT INTO
notes_categories (name, description, puid)
VALUES
('技术', '关于技术的文章', '0'),
('生活', '关于生活的文章', '1'),
('旅游', '关于旅游的文章', '2');
创建了一个数据库连接
const mysql = require("mysql2");
// 连接数据库
const connection = mysql.createConnection({
host: "localhost",
user: "notes_app",
password: "notes_app",
database: "notes_app"
});
module.exports = connection.promise();
const Router = require("@koa/router");
const db = require("./db");
const router = new Router({ prefix: "/api" });
// 获取文章分类列表
router.get("/categories", async ctx => {
try {
const [rows] = await db.query("SELECT * FROM notes_categories");
console.log(rows);
ctx.body = rows;
} catch (err) {
ctx.throw(500, err);
}
});
启动一个监听服务: app.listen(3000)
const Koa = require("koa");
const bodyParser = require("koa-bodyparser");
const app = new Koa();
const homeRouter = require("./router");
app.use(bodyParser());
app.use(homeRouter.routes()).use(homeRouter.allowedMethods());
app.listen(3000, () => {
console.log("服务器已经3000端口启动!");
});
主要添加start命令:"start": "node app.js",
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js",
"stop": "node stop",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@koa/router": "^12.0.0",
"koa": "^2.14.2",
"koa-bodyparser": "^4.4.1",
"koa-json-error": "^3.1.2",
"koa-router": "^12.0.0",
"koa-router-swagger": "^1.2.3",
"mysql2": "^3.6.0",
"swagger-ui-dist": "^5.4.2"
}
}
pnpm start