OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

node.js error when using: npm run dev, TypeError: require(...) is not a function

  • Thread starter Thread starter robbe505
  • Start date Start date
R

robbe505

Guest
im working on my first project, added a database and im trying to make a login page.

while i try to run it using npm run dev. it gives me an error exact error is at the bottom

I dont know what causes this and how i can fix this can somebody help please?

the database structure looks like this:Database

The folder structure of my app looks like this: folderstructure

my config/database.js is this:

Code:
const { Sequelize } = require('sequelize');

const sequelize = new Sequelize('dfddatabase', 'root', 'Password', {
  host: 'localhost',
  dialect: 'mariadb',
  logging: false
});

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

module.exports = { sequelize, connectDb };

The models/index.js:

Code:
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('mysql://user:password@localhost:3306/database_name', {
  dialect: 'mariadb',
});

// Import models
const User = require('./user')(sequelize, DataTypes);
const CsvFile = require('./csvfile')(sequelize, DataTypes);
const PasswordReset = require('./passwordreset')(sequelize, DataTypes);
const Setting = require('./setting')(sequelize, DataTypes);
const ScharnierType = require('./scharniertype')(sequelize, DataTypes);
const DeurType = require('./deurtype')(sequelize, DataTypes);

// Define associations
User.hasMany(CsvFile, { foreignKey: 'user_id' });
CsvFile.belongsTo(User, { foreignKey: 'user_id' });

User.hasOne(Setting, { foreignKey: 'user_id' });
Setting.belongsTo(User, { foreignKey: 'user_id' });

Setting.belongsToMany(ScharnierType, { through: 'settings_scharniertypes' });
ScharnierType.belongsToMany(Setting, { through: 'settings_scharniertypes' });

Setting.belongsToMany(DeurType, { through: 'settings_deurtypes' });
DeurType.belongsToMany(Setting, { through: 'settings_deurtypes' });

module.exports = {
  sequelize,
  Sequelize,
  User,
  CsvFile,
  PasswordReset,
  Setting,
  ScharnierType,
  DeurType
};


sequelize.sync({ force: true }).then(() => {
    console.log("Database & tables created!");
  });

the modules of user.js:

Code:
module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      email: {
        type: DataTypes.STRING,
        unique: true,
        allowNull: false,
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      createdAt: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
      },
      updatedAt: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
      },
    }, {
      tableName: 'users'
    });
    return User;
  };

my routes/index.js:

Code:
const express = require('express');
const router = express.Router();

// Index Page
router.get('/', (req, res) => res.render('index', { title: 'Home' }));

module.exports = router;

my app.js:

Code:
const express = require('express');
const session = require('express-session');
const flash = require('connect-flash');
const passport = require('passport');
const path = require('path');
const { connectDb } = require('./models');
const sequelize = require('./config/database');

const app = express();

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:4000`);
});


// Passport Config
require('./config/passport')(passport);

// EJS
app.set('view engine', 'ejs');

// Static Files
app.use(express.static(path.join(__dirname, 'public')));

// Bodyparser
app.use(express.urlencoded({ extended: false }));

// Express session
app.use(
  session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
  })
);

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());

// Connect flash
app.use(flash());

// Global variables
app.use((req, res, next) => {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  res.locals.user = req.user || null;
  next();
});

// Routes
app.use('/', require('./routes/index'));
app.use('/auth', require('./routes/auth'));
app.use('/password', require('./routes/password'));

const PORT = process.env.PORT || 5000;

connectDb().then(() => {
  app.listen(PORT, console.log(`Server started on port ${PORT}`));
});

my package.json:

Code:
{
  "name": "loginapp",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon app.js",
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "connect-flash": "^0.1.1",
    "dotenv": "^16.4.5",
    "ejs": "^3.1.10",
    "express": "^4.19.2",
    "express-session": "^1.18.0",
    "jsonwebtoken": "^9.0.2",
    "mariadb": "^3.3.1",
    "mysql2": "^3.10.1",
    "nodemailer": "^6.9.14",
    "nodemailer.js": "^0.0.2-security",
    "passport": "^0.7.0",
    "passport-local": "^1.0.0",
    "sequelize": "^6.37.3"
  }
}

and in my console cmd i get this:

Code:
C:\Users\Robbe\Downloads\LoginApp>npm run dev

> [email protected] dev
> nodemon app.js

[nodemon] 3.1.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node app.js`
C:\Users\DelsoirRobbe\Downloads\LoginApp\models\index.js:7
const User = require('./user')(sequelize, DataTypes);
                              ^

TypeError: require(...) is not a function
    at Object.<anonymous> (C:\Users\DelsoirRobbe\Downloads\LoginApp\models\index.js:7:31)
    at Module._compile (node:internal/modules/cjs/loader:1358:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)
    at Module.load (node:internal/modules/cjs/loader:1208:32)
    at Module._load (node:internal/modules/cjs/loader:1024:12)
    at Module.require (node:internal/modules/cjs/loader:1233:19)
    at require (node:internal/modules/helpers:179:18)
    at Object.<anonymous> (C:\Users\DelsoirRobbe\Downloads\LoginApp\app.js:6:23)
    at Module._compile (node:internal/modules/cjs/loader:1358:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)

Node.js v20.13.1
[nodemon] app crashed - waiting for file changes before starting...

if somebody can help or need any more info, i would be very greatful!!

i tried replacing my models, i tried using diffrent localhost things, changed my database password, installed npm packages again, but it didnt change anything..

<p>im working on my first project, added a database and im trying to make a login page.</p>
<p>while i try to run it using npm run dev. it gives me an error exact error is at the bottom</p>
<p>I dont know what causes this and how i can fix this can somebody help please?</p>
<p>the database structure looks like this:<a href="https://i.sstatic.net/gYVA5V4I.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gYVA5V4I.png" alt="Database" /></a></p>
<p>The folder structure of my app looks like this:
<a href="https://i.sstatic.net/0kBF6NYC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0kBF6NYC.png" alt="folderstructure" /></a></p>
<p>my config/database.js is this:</p>
<pre><code>const { Sequelize } = require('sequelize');

const sequelize = new Sequelize('dfddatabase', 'root', 'Password', {
host: 'localhost',
dialect: 'mariadb',
logging: false
});

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

module.exports = { sequelize, connectDb };
</code></pre>
<p>The models/index.js:</p>
<pre><code>const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('mysql://user:password@localhost:3306/database_name', {
dialect: 'mariadb',
});

// Import models
const User = require('./user')(sequelize, DataTypes);
const CsvFile = require('./csvfile')(sequelize, DataTypes);
const PasswordReset = require('./passwordreset')(sequelize, DataTypes);
const Setting = require('./setting')(sequelize, DataTypes);
const ScharnierType = require('./scharniertype')(sequelize, DataTypes);
const DeurType = require('./deurtype')(sequelize, DataTypes);

// Define associations
User.hasMany(CsvFile, { foreignKey: 'user_id' });
CsvFile.belongsTo(User, { foreignKey: 'user_id' });

User.hasOne(Setting, { foreignKey: 'user_id' });
Setting.belongsTo(User, { foreignKey: 'user_id' });

Setting.belongsToMany(ScharnierType, { through: 'settings_scharniertypes' });
ScharnierType.belongsToMany(Setting, { through: 'settings_scharniertypes' });

Setting.belongsToMany(DeurType, { through: 'settings_deurtypes' });
DeurType.belongsToMany(Setting, { through: 'settings_deurtypes' });

module.exports = {
sequelize,
Sequelize,
User,
CsvFile,
PasswordReset,
Setting,
ScharnierType,
DeurType
};


sequelize.sync({ force: true }).then(() => {
console.log("Database & tables created!");
});

</code></pre>
<p>the modules of user.js:</p>
<pre><code>module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
},
}, {
tableName: 'users'
});
return User;
};

</code></pre>
<p>my routes/index.js:</p>
<pre><code>const express = require('express');
const router = express.Router();

// Index Page
router.get('/', (req, res) => res.render('index', { title: 'Home' }));

module.exports = router;
</code></pre>
<p>my app.js:</p>
<pre><code>const express = require('express');
const session = require('express-session');
const flash = require('connect-flash');
const passport = require('passport');
const path = require('path');
const { connectDb } = require('./models');
const sequelize = require('./config/database');

const app = express();

app.listen(PORT, () => {
console.log(`Server running on http://localhost:4000`);
});


// Passport Config
require('./config/passport')(passport);

// EJS
app.set('view engine', 'ejs');

// Static Files
app.use(express.static(path.join(__dirname, 'public')));

// Bodyparser
app.use(express.urlencoded({ extended: false }));

// Express session
app.use(
session({
secret: 'secret',
resave: true,
saveUninitialized: true
})
);

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());

// Connect flash
app.use(flash());

// Global variables
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});

// Routes
app.use('/', require('./routes/index'));
app.use('/auth', require('./routes/auth'));
app.use('/password', require('./routes/password'));

const PORT = process.env.PORT || 5000;

connectDb().then(() => {
app.listen(PORT, console.log(`Server started on port ${PORT}`));
});
</code></pre>
<p>my package.json:</p>
<pre><code>{
"name": "loginapp",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "nodemon app.js",
"start": "node app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"bcryptjs": "^2.4.3",
"connect-flash": "^0.1.1",
"dotenv": "^16.4.5",
"ejs": "^3.1.10",
"express": "^4.19.2",
"express-session": "^1.18.0",
"jsonwebtoken": "^9.0.2",
"mariadb": "^3.3.1",
"mysql2": "^3.10.1",
"nodemailer": "^6.9.14",
"nodemailer.js": "^0.0.2-security",
"passport": "^0.7.0",
"passport-local": "^1.0.0",
"sequelize": "^6.37.3"
}
}
</code></pre>
<p>and in my console cmd i get this:</p>
<pre><code>
C:\Users\Robbe\Downloads\LoginApp>npm run dev

> [email protected] dev
> nodemon app.js

[nodemon] 3.1.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node app.js`
C:\Users\DelsoirRobbe\Downloads\LoginApp\models\index.js:7
const User = require('./user')(sequelize, DataTypes);
^

TypeError: require(...) is not a function
at Object.<anonymous> (C:\Users\DelsoirRobbe\Downloads\LoginApp\models\index.js:7:31)
at Module._compile (node:internal/modules/cjs/loader:1358:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)
at Module.load (node:internal/modules/cjs/loader:1208:32)
at Module._load (node:internal/modules/cjs/loader:1024:12)
at Module.require (node:internal/modules/cjs/loader:1233:19)
at require (node:internal/modules/helpers:179:18)
at Object.<anonymous> (C:\Users\DelsoirRobbe\Downloads\LoginApp\app.js:6:23)
at Module._compile (node:internal/modules/cjs/loader:1358:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)

Node.js v20.13.1
[nodemon] app crashed - waiting for file changes before starting...
</code></pre>
<p>if somebody can help or need any more info, i would be very greatful!!</p>
<p>i tried replacing my models, i tried using diffrent localhost things, changed my database password, installed npm packages again, but it didnt change anything..</p>
 

Latest posts

Top