一、安装依赖
安装 @fastify/mysql
pnpm add @fastify/mysql
二、示例
1. 创建 index.js
连接数据库,确保已经启动数据库,输入数据库的账号,密码,域名,端口,库名。
import Fastify from "fastify";import routes from "./routes.js";import fastifyMysql from "@fastify/mysql";const fastify = Fastify({logger: true,});/** 连接数据库 */fastify.register(fastifyMysql, {host: "127.0.0.1",port: 3307,user: "root",password: "111111",database: "twogod",charset: "utf8mb4",promise: true,});/** 接受所有媒体类型 */fastify.addContentTypeParser("*", function (request, payload, done) {var data = "";payload.on("data", (chunk) => {data += chunk;});payload.on("end", () => {done(null, data);});});/** 注册接口 */fastify.register(routes);/** 启动服务 */const start = async () => {try {await fastify.listen({ port: 3000 });console.log("webserver is runing");} catch (err) {console.log(err);}};start();
2. 创建 routes.js
async function routes(fastify, options) {/** 登录 */fastify.post("/login", async (req, res, done) => {const { username, password } = req.body;try {const result = await fastify.mysql.query("SELECT * FROM sys_admins WHERE username=? AND PASSWORD=?",[username, password]);if (result[0].length > 0) {return {code: 200,msg: "success",data: result[0][0],};} else {return {code: 500,msg: "账号或密码错误!",data: null,};}} catch (err) {return {code: 500,msg: "error",data: err,};}});}export default routes;