mysql - 如何在http服务器开始接受请求之前建立mysql2连接?

标签 mysql node.js

const http = require('http');
var mysql2 = require('mysql2/promise');
var mysql2Conn;

const httpServer = http.createServer(function(req,res){
    // error handler
    // handlers
    // req.on('data' ...
    // req.on('end' ...

}).listen(config_private.localPort, async function (err){
    // error handler
};

上面的代码应该放在哪里

mysql2Conn= await mysql2.createConnection({..params..});

让服务器.listen并让http.createServer的eventHandler在sqlConn1准备好后接受http请求?

最佳答案

连接到db后,您可以监听,例如:

const http = require('http');
var mysql2 = require('mysql2/promise');
var mysql2Conn;

const httpServer = http.createServer(function(req,res){
  // error handler
  // handlers
  // req.on('data' ...
  // req.on('end' ...
});

async function init() {
  try {
    mysql2Conn= await mysql2.createConnection({..params..});
    httpServer.listen(config_private.localPort, async function (err){
      // error handler
    });
  } catch(e) {
    console.log('db connection failed');
  }
}

init();

关于mysql - 如何在http服务器开始接受请求之前建立mysql2连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325280/

相关文章:

使用 mySQL 的 php 树递归

mysql - SQL,按 MAX 查找组的计数

node.js - 使用nodejs在mongodb中插入嵌入文档

node.js - 引擎.io/wss/SSL/HTTP : how to configure?

javascript - Mongoose 错误 : JavaScript heap out of memory

如果第二个表没有匹配项,Mysql 返回零行

mysql - Sequelize 使用 MySQL 抛出断言错误

mysql - 如何正确使用不同的 group_concat - MYSQL

javascript - 在不同文件中导出不同路由的实际函数

node.js - MongoDB : How to multiply a field that appears only in $project?