在CentOS上配置Node.js应用程序以连接到数据库通常涉及以下几个步骤:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
安装数据库:
MySQL:
sudo yum install -y mysql-server
sudo systemctl start mysqld
sudo systemctl enable mysqld
sudo yum install -y postgresql-server
sudo systemctl start postgresql
sudo systemctl enable postgresql
sudo yum install -y mongodb
npm install mysql2
npm install pg
npm install mongoose
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to database: ', err);
return;
}
console.log('Connected to database!');
});
const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database',
port: 5432
});
client.connect((err) => {
if (err) {
console.error('Error connecting to database: ', err);
return;
}
console.log('Connected to database!');
});
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB!');
});
为了提高安全性,避免在代码中硬编码数据库凭据,建议使用环境变量来管理这些敏感信息。例如,可以创建一个 .env 文件:
DATABASE_HOST=localhost
DATABASE_USER=your_username
DATABASE_PASSWORD=your_password
DATABASE_NAME=your_database
然后在你的Node.js应用程序中使用 dotenv 包来加载这些环境变量:
require('dotenv').config();
确保你的应用程序可以访问数据库,并且数据库服务正在运行。然后,你可以运行你的Node.js应用程序:
node app.js