从nodejs连接到Mysql时出错

时间:2018-06-09 20:20:30

标签: mysql node.js

我最近启动了node-js,我试图将我的nodejs服务器与mysql连接。 问题是我收到错误,我真的不知道为什么,我正在使用phpmyadmin。

Phpmyadmin详情

user:root

host:localhost

密码未设置

This is the image of my phpmyadmin database

This is the settings of my phpmyadmin console

This is the terminal where it is showing error connecting to DB

index.js

    var express = require("express");
    var app = express();
    var mysql = require('mysql');

     var port = process.env.PORT || 3000;

     var connection = mysql.createConnection({
     host: "localhost",
     user: "root",
     database: "learning",
     });

   connection.connect(function(err){
    if(err) {
   console.log('Error connecting to Db');
    return;
    }

  console.log('Connection established');
  console.log('3');

  connection.end(function(err) {
  console.log('Connection closed');
  console.log('4');

  process.exit();
  });
  });

  app.listen(port,function(err1){
  console.log("Listening on the port 3000");
  });

2 个答案:

答案 0 :(得分:2)

从节点js连接到mysql,您习惯从节点js连接到mysql

/config
  /database.js
/server.js
/.env

const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);

server.listen(process.env.ServerPort, '0.0.0.0', () => {
  logger.info(`Express server listening on port ${process.env.ServerPort}`);
});

运行此命令

node server.js

database.js文件

const My = require('jm-ez-mysql');

// Init DB Connection
const connection = My.init({
  host: process.env.DBHOST,
  user: process.env.DBUSER,
  password: process.env.DBPASSWORD,
  database: process.env.DATABASE,
  dateStrings: true,
  charset: 'utf8mb4',
  timezone: 'utc',
  multipleStatements: true,
  connectTimeout: 100 * 60 * 1000,
  acquireTimeout: 100 * 60 * 1000,
  timeout: 100 * 60 * 1000,
});

module.exports = {
  connection,
};

答案 1 :(得分:0)

我已将端口从phpmyadmin mysql的默认3306更改为3308

因此我添加了端口:3308并开始工作。

 var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 database: "learning",
 port: 3308
 });