Node.js 在 Linux 上如何配置数据库连接

823
2025/4/9 15:32:06
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 Linux 上配置 Node.js 应用程序以连接到数据库,通常涉及以下几个步骤:

  1. 安装数据库:首先,你需要在 Linux 服务器上安装数据库。例如,如果你使用的是 MySQL,你可以使用包管理器来安装它:

    sudo apt update
    sudo apt install mysql-server
    

    对于 PostgreSQL:

    sudo apt update
    sudo apt install postgresql postgresql-contrib
    

    安装完成后,启动数据库服务并设置开机自启:

    sudo systemctl start mysql
    sudo systemctl enable mysql
    

    或者对于 PostgreSQL:

    sudo systemctl start postgresql
    sudo systemctl enable postgresql
    
  2. 创建数据库和用户:使用数据库管理工具(如 phpMyAdmin、pgAdmin 或命令行)创建一个新的数据库和一个用户,并授予该用户访问数据库的权限。

    例如,在 MySQL 中:

    CREATE DATABASE mydatabase;
    CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
    GRANT ALL PRIVILEGES ON mydatabase.* TO 'myuser'@'localhost';
    FLUSH PRIVILEGES;
    

    在 PostgreSQL 中:

    CREATE DATABASE mydatabase;
    CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypassword';
    GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;
    
  3. 安装 Node.js 数据库驱动:在你的 Node.js 应用程序中,你需要安装相应的数据库驱动。例如,如果你使用的是 MySQL,你可以使用 mysqlmysql2 包:

    npm install mysql2
    

    对于 PostgreSQL,你可以使用 pg 包:

    npm install pg
    
  4. 配置数据库连接:在你的 Node.js 应用程序中,创建一个配置文件或在代码中直接设置数据库连接参数。例如,对于 MySQL:

    const mysql = require('mysql2');
    
    const connection = mysql.createConnection({
      host: 'localhost',
      user: 'myuser',
      password: 'mypassword',
      database: 'mydatabase'
    });
    
    connection.connect(error => {
      if (error) throw error;
      console.log("Successfully connected to the database.");
    });
    

    对于 PostgreSQL:

    const { Pool } = require('pg');
    
    const pool = new Pool({
      user: 'myuser',
      host: 'localhost',
      database: 'mydatabase',
      password: 'mypassword',
      port: 5432,
    });
    
    pool.connect(error => {
      if (error) throw error;
      console.log("Successfully connected to the database.");
    });
    
  5. 使用环境变量管理敏感信息:为了安全起见,不要在代码中硬编码数据库凭据。相反,使用环境变量来存储这些信息,并在你的 Node.js 应用程序中读取它们。你可以使用 .env 文件和 dotenv 包来管理环境变量。

    安装 dotenv

    npm install dotenv
    

    在你的应用程序的入口文件(如 app.jsindex.js)顶部加载 .env 文件:

    require('dotenv').config();
    

    然后在你的代码中使用 process.env 来访问环境变量:

    const connection = mysql.createConnection({
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME
    });
    
  6. 测试连接:运行你的 Node.js 应用程序并测试数据库连接是否成功。

请注意,这些步骤可能会根据你使用的具体数据库和 Node.js 库有所不同。始终参考你所使用的数据库和库的官方文档来获取最准确的指导。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: linux如何进入图形化界面