【发布时间】:2021-08-19 08:09:44
【问题描述】:
我正在从一个准备好的应用程序中学习并尝试建立连接,以便应用程序开始工作并保存数据。
picture of the hostname and port
我完成了连接,还用我需要的两个表创建了一个“员工数据库”
服务器在 localhost 3000 上运行,前端正在侦听端口 4200。这是用于连接和创建数据库/模式的代码。
config.json
{
"host": "localhost",
"user": "cveto",
"database": "employees",
"password": "1234567"
}
database.js 创建池
const mysql = require('mysql2');
const config = require('../config/config.json');
const pool = mysql.createPool({
host: config.host,
user: config.user,
database: config.database,
password: config.password,
});
module.exports = pool.promise();
还有一些查询模型
const db = require('../util/database');
module.exports = class Employee {
constructor(names, address, number, salary) {
this.names = names;
this.address = address;
this.number = number;
this.salary = salary;
}
static fetchAll() {
return db.execute('SELECT * FROM employees');
}
static save(employee) {
return db.execute(
'INSERT INTO employees (names, address, number, salary) VALUES (?, ?, ?, ?)',
[employee.names, employee.address, employee.number, employee.salary]
);
}
static delete(id) {
return db.execute('DELETE FROM employees WHERE id = ?', [id]);
}
};
我只想知道如何建立连接,以便应用程序运行并将用户和新员工保存到我的数据库中。代码来自公共存储库,因此代码正在运行,现在它来自数据库或服务器连接的代码。
【问题讨论】:
-
您永远不应该在 Web 应用程序和数据库之间建立直接连接,因为您需要将数据库凭据传输到前端,以便每个可能的攻击者都可以读取它们。通常您应该使用后端来“保护”您的数据库,并在前端和后端之间进行一些授权。 (抱歉没有回答实际问题)
标签: javascript mysql sql node.js angular