Koa
...大约 2 分钟
Koa
上下文(Context)
Context 将 node 的 request 和 response 对象封装到单个对象中,为编写 Web 应用程序和 API 提供了许多有用的方法。 这些操作在 HTTP 服务器开发中频繁使用,它们被添加到此级别而不是更高级别的框架,这将强制中间件重新实现此通用功能
提示
每个_ 请求都将创建一个 Context,并在中间件中作为接收器引用,或者 ctx 标识符
app.use(async (ctx) => {
ctx; // 这是 Context
ctx.request; // 这是 koa Request
ctx.response; // 这是 koa Response
});
为方便起见许多上下文的访问器和方法直接委托给它们的 ctx.request 或 ctx.response ,不然的话它们是相同的。
request
连接 MySql
项目中引入 mysql
npm install mysql
数据库配置
src/config/default.ts
点击查看代码
const config = {
//启动端口
port: 3000,
//数据库配置
database: {
DATABASE: "db_name",
USERNAME: "root",
PASSWORD: "*****",
PORT: "3306",
HOST: "localhost",
},
};
module.exports = config;
创建连接池
src/mysql/index.ts
点击查看代码
import { getCombinedNodeFlags } from "typescript";
const mysql = require("mysql");
const config = require("../config/default");
var pool = mysql.createPool({
host: config.database.HOST,
user: config.database.USERNAME,
password: config.database.PASSWORD,
database: config.database.DATABASE,
});
class MySql {
constructor() {}
query() {
return new Promise((resolve, reject) => {
pool.query(
"SELECT * FROM `db_name`.`student` LIMIT 0,1000",
(error: any, results: any) => {
if (error) {
console.log(error);
}
resolve(results);
console.log("The solution is: ", results);
}
);
});
}
}
module.exports = new MySql();
提示
createPool 创建连接池
在开发 web 应用程序时,连接池是一个很重要的概念。建立一个数据库连接所消耗的性能成本是很高的。在服务器应用程序中,如果为每一个接收到的客户端请求都建立一个或多个数据库连接,将严重降低应用程序性能。
因此在服务器应用程序中通常需要为多个数据库连接创建并维护一个连接池,当连接不再需要时,这些连接可以缓存在连接池中,当接收到下一个客户端请求时,从连接池中取出连接并重新利用,而不需要再重新建立连接。
MySQL client 报错问题解决方案
Client does not support authentication protocol requested by server; consider upgrading
终端执行数据库登陆
mysql -u root -p
切换到 mysql
use mysql;
alter user 'root'@'localhost' identified with mysql_native_password by '123456';
flush privileges;
Powered by Waline v2.15.5