2023-08-29 09:50阅读: 18评论: 0推荐: 0

快速入门:掌握Koa基础使用技巧

前言

本文主要是学习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');

数据库使用

新建db.js

创建了一个数据库连接

const mysql = require("mysql2");

// 连接数据库
const connection = mysql.createConnection({
  host: "localhost",
  user: "notes_app",
  password: "notes_app",
  database: "notes_app"
});

module.exports = connection.promise();
新建route.js
  1. prefix: 表示添加接口前缀
  2. 使用数据:const [rows] = await db.query("SELECT * FROM notes_categories");
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.js

启动一个监听服务: 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端口启动!");
});

启动服务

修改package.json

主要添加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
访问查看结果

 

本文作者:不随。

本文链接:https://www.cnblogs.com/tmblog/p/17849255.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   不随。  阅读(18)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.