繁体   English   中英

无法使用 NodeJS、Express 连接到 MySQL

[英]Cannot connect to MySQL using NodeJS, Express

I'm trying to connect to MySQL via nodeJS app using express for server, ive read the mysql npm documentation in order to begin connection but it seems like i get the error from the callback function i wrote inside createConnection.connect() and im using phpmyadmin 只是为了看结果和图表

这是我的代码:

const express = require('express');
const app = express();
const mysql = require('mysql'); 
require('dotenv').config();
const workers = require('./routes/workers');


app.use('/', workers);


const DB = mysql.createConnection({
    host     : 'localhost',
   user     : 'root',
  charset: 'utf8_general_ci',
  password: '',

});

DB.connect((err) => {
     throw `error: ${err}`
 });

 app.listen(process.env._PORT, () => {
     console.log(`Server is running on ${process.env._PORT}`);
 });

连接后您没有检查错误 您必须检查数据库连接时是否有任何错误,如下所示。

DB.connect((err) => {
     if(err){
        throw `error: ${err}`       
     }
     console.log("Database connected successfully");
 });

安装sequelizejs、mysql、mysql2库

var Sequelize = require('sequelize');
var sequelize = new Sequelize(dbName, username, password,{ host: localhost,
    // data type
    dialect: mysql,
});

可以使用.authenticate() function 来测试连接是否OK:

try {
  await sequelize.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM