Alex McLemon
Alex McLemon

Reputation: 15

How to fix "err is not defined" error in Nodejs

I'm trying to establish a connection to mysql database in Nodejs but it won't compile as "err is undefined". I'm fairly new to Node.js, but I thought this was the appropriate way to handle errors, even with the mysql package, which is the only difference from my other projects where I did not encounter this issue.

throw err; // Rethrow non-MySQL errors ^

ReferenceError: err is not defined

const express = require('express');
const mysql = require('mysql');

//Create connection
const db = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '123456',
    database: 'ca1903'
});

//Connect
db.connect(() => {
    if(err){
        console.log(err);
    }
    console.log('MySql Connected');
});

const app = express();

//create DB
app.get('/createdb', () => {
    let sql = 'CREATE DATABASE ca1903';
    db.query(sql, (err, result) => {
        if(err){
            console.log(err);
        }
        console.log(result);
        res.send('database created....');
    });
});

Upvotes: 1

Views: 12606

Answers (1)

Sreehari
Sreehari

Reputation: 1370

You were missing err parameter in the db.connect call. It should be in the below way.

// Connect
db.connect((err) => {
  if(err){
    console.log(err);
  }
  console.log('MySql Connected');
});

Upvotes: 3

Related Questions