跳至主要內容
Node.js 操作 MySQL(mysql2 实战)

1. 安装与连接

npm install mysql2
const mysql = require('mysql2/promise');  // 使用 Promise 版本(推荐)

// 连接配置(类似前端请求的 baseURL + 鉴权)
const pool = mysql.createPool({
    host: 'localhost',      // 数据库主机
    port: 3306,             // MySQL 默认端口
    user: 'root',           // 用户名
    password: '123456',     // 密码
    database: 'my_app',     // 数据库名
    waitForConnections: true,
    connectionLimit: 10,    // 连接池大小
    queueLimit: 0,
});

// 测试连接
async function testConnection() {
    try {
        const connection = await pool.getConnection();
        console.log('数据库连接成功 ✅');
        connection.release();
    } catch (err) {
        console.error('数据库连接失败 ❌', err);
    }
}

Mr.Ding大约 3 分钟mysqlNode.jsmysql2全栈前端转后端
Node.js 操作 Redis(ioredis 实战)

1. 安装与连接

npm install ioredis
const Redis = require('ioredis');

// 连接 Redis(默认 localhost:6379)
const redis = new Redis();

// 指定配置
const redis = new Redis({
    host: 'localhost',
    port: 6379,
    password: '123456',
    db: 0,                    // 数据库编号(默认 0~15)
    retryStrategy: (times) => {
        // 断线重连策略
        return Math.min(times * 50, 2000);  // 最多等 2 秒
    },
});

// 连接字符串方式
const redis = new Redis('redis://:password@localhost:6379/0');

// 测试连接
redis.ping().then(res => {
    console.log('Redis 连接', res === 'PONG' ? '✅' : '❌');
});

Mr.Ding大约 4 分钟redisNode.jsioredis全栈前端转后端