英文:
Connecting Express server and mariadb
问题
Express服务器抛出的错误是数据库连接池超时。你可以尝试以下几种方法来解决这个问题:
- 
增加连接池的限制: 你可以尝试增加连接池的限制,以允许更多的并发连接。在你的Express服务器代码中,connection对象的connectionLimit属性设置了连接池的最大连接数。你可以尝试增加这个值,例如设置为更高的数字,以确保有足够的数据库连接可用。
var connection = mariadb.createPool({ host: "localhost", user: "user", password: "pass", database: "users", connectionLimit: 10 // 例如,将连接限制增加到10 }); - 
检查数据库连接配置: 确保数据库主机地址、用户名和密码等数据库连接配置是正确的。你已经提到可以从控制台成功连接到数据库,但仍然需要确保这些配置正确。
 - 
检查数据库状态: 检查数据库服务器的状态,确保它正常运行,没有资源不足或其他问题。你可以尝试从命令行或其他数据库客户端连接并执行一些查询,以确保数据库能够正常响应。
 - 
检查数据库连接池配置: 除了连接限制外,还可以检查其他连接池配置项,例如最小空闲连接数、连接超时等。根据你的需求进行适当的配置。
 - 
查看数据库错误日志: 如果问题仍然存在,查看数据库服务器的错误日志,可能会提供更多关于连接超时的详细信息,以帮助诊断问题。
 
请注意,连接超时通常是由于数据库服务器资源不足或配置问题引起的。根据你的服务器环境和需求,可能需要调整连接池配置和数据库服务器配置来解决这个问题。
英文:
I am trying to make a very simple login webpage, no security or anything like that. My system right now consists of an OpenSuse server with a mariadb database and an Express server and an HTML file for the client.
Express server:
<!-- language: lang-js -->
const mariadb = require('mariadb');
const express = require('express');
const session = require("express-session");
const http = require('http');
const app = express();
app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({
  extended: true
}));
const expresServer = http.createServer(app);
var connection = mariadb.createPool({
  host: "localhost",
  user: "user",
  password: "pass",
  database: "users",
  connectionLimit: 2
});
app.use(express.static(__dirname + '/client'))
app.get("/", (req, res) => {
  res.sendFile(__dirname + '/client/login.html')
})
app.post('/auth', function(request, response) {
  // Capture the input fields
  let username = request.body.username;
  let password = request.body.password;
  // Ensure the input fields exists and are not empty
  if (username && password) {
    // Execute SQL query that'll select the account from the database based on the specified username and password
    connection.query('SELECT * FROM USERS WHERE User = ? AND Pass = ?', [username, password], function(error, results, fields) {
      // If there is an issue with the query, output the error
      if (error) throw error;
      // If the account exists
      if (results.length > 0) {
        // Authenticate the user
        request.session.loggedin = true;
        request.session.username = username;
        // Redirect to home page
        response.redirect('/main');
      } else {
        response.send('Incorrect Username and/or Password!');
      }
      response.end();
    });
  } else {
    response.send('Please enter Username and Password!');
    response.end();
  }
});
app.get('/main', function(request, response) {
  // If the user is loggedin
  if (request.session.loggedin) {
    // Output username
    response.send('Welcome back, ' + request.session.username + '!');
  } else {
    // Not logged in
    response.send('Please login to view this page!');
  }
  response.end();
});
expresServer.listen(3000, () => {
  console.log("Listening on 3000");
})
HTML login:
<!-- language: lang-html -->
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>UAV5G</title>
  <link rel="shortcut icon" href="/imgs/Logo.png" />
  <link rel="stylesheet" href="css/login.css" media="screen" />
  <link rel="stylesheet" href="css/all.min.css" />
</head>
<body>
  <div class="elem-box">
    <div class="login-box">
      <h2>Login</h2>
      <form action="/auth" method="post">
        <div class="user-box">
          <input type="text" name="username" id="username" required>
          <label for="username">Username</label>
        </div>
        <div class="user-box">
          <input type="password" name="password" id="password" required>
          <label for="password">Password</label>
        </div>
        <input class="login" type="submit" value="Login">
      </form>
    </div>
    <img src="/imgs/Logo.png" class="logo">
  </div>
</body>
</html>
I do not think CSS is needed.
The problem here is that the Express server throws this error:
/home/node/Server/node_modules/mariadb/lib/misc/errors.js:61
  return new SqlError(msg, sql, fatal, info, sqlState, errno, additionalStack, addHeader);
         ^
SqlError: (conn=-1, no: 45028, SQLState: HY000) retrieve connection from pool timeout after 10010ms
    (pool connections: active=0 idle=0 limit=2)
    at module.exports.createError (/home/node/Server/node_modules/mariadb/lib/misc/errors.js:61:10)
    at Pool._requestTimeoutHandler (/home/node/Server/node_modules/mariadb/lib/pool.js:344:26)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7) {
  sqlMessage: 'retrieve connection from pool timeout after 10010ms\n' +
    '    (pool connections: active=0 idle=0 limit=2)',
  sql: null,
  fatal: false,
  errno: 45028,
  sqlState: 'HY000',
  code: 'ER_GET_CONNECTION_TIMEOUT'
}
I do not know why, I can connect to the database from console using that username and password and adding connectTimeout: 10000 (or higher) does not help.
答案1
得分: 0
我认为在获取数据后,你必须释放连接。可能会导致你遇到所有的问题。
connection.query('SELECT * FROM USERS WHERE User = ? ...', function (error, results, fields) {
// 完成连接后,释放它。
connection.release();
英文:
I think you must have to release the connection after you get your data. Might be causing all the troubles for you.
connection.query('SELECT * FROM USERS WHERE User = ? ...', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
答案2
得分: 0
使用mariadb连接器时出现错误:
有两种不同的实现方式:promise 和 callback。
- promise:
const mariadb = require('mariadb'); - callback:
const mariadb = require('mariadb/callback'); 
问题在于你使用了promise实现,然后调用了一个回调方法:
connection.query('SELECT * FROM USERS WHERE User = ? AND Pass = ?', [username, password], function(error, results, fields) {
所以你要么将其改为promise,要么使用callback实现。
英文:
There is an error using mariadb connector:
there is 2 different implementation : promise and callback.
- promise : 
const mariadb = require('mariadb'); - callback : 
const mariadb = require('mariadb/callback'); 
problem here is that you use promise implementation then call a callback method:
connection.query('SELECT * FROM USERS WHERE User = ? AND Pass = ?', [username, password], function(error, results, fields) {
so either you change that to promise, or use callback implementation
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论