I am trying to connect my school project to a mysql database but I always get the error "TypeError: connection.connect is not a function". I am not quite sure how to fix it. I hope someone is able to solve this.
My index.js
const express = require('express');
const app = express();
var connection = require('./database');
app.use(express.static('public'));
app.get('/form', (req,res) =>{
res.sendFile(__dirname '/public/index.html' );
console.log(req.url);
console.log(req.path);
})
app.listen(4000, () =>{
console.log("Server listening on port 4000");
connection.connect((err) => {
if(err) throw err;
console.log("Connected");
})
});
my database.js
let mysql = require('mysql');
module.exports = () => {
return mysql.createConnection({
host: 'localhost',
database: 'minigames',
user: 'root',
password: 'root'
})}```
CodePudding user response:
connection
is the value exported from the database module.
The value you assigned to module.exports
there is a function that you defined.
It is a plain, ordinary function and you have no assigned a connect
property to it.
I'm guessing that connect
is a property on the return value of mysql.createConnection
, but if you want to access that object then, you need to call the function you defined in order to get that object.
CodePudding user response:
app.listen(4000, () =>{
console.log("Server listening on port 4000");
connection().connect((err) => {
if(err) throw err;
console.log("Connected");
})
});
This will work .you were just exporting function you were not calling that function i would suggest you to follow documentation of npm mysql