2

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:

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:

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:

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:

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:

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:

{
  "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:


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..

1
  • Thank you for sharing the code. Try replicating the issue in a new project which only has the problematic code. Commented Jun 21, 2024 at 13:08

1 Answer 1

0

If you initially name a file with an uppercase letter and then change it to a lowercase letter, it might not recognize the change, causing the import to break. To resolve this issue, try renaming the file to something completely different, then change the name back to the original name. This should allow the file to be found correctly in the import path.

Sign up to request clarification or add additional context in comments.

6 Comments

where do you say i would need to rename the file? thank you
It's a chance if you named user.js file User.js initially, then renamed it to user.js, it doesn't accept the new name. I run into this often when working with React, and forget to name a component with a capital letter, I get a similar error, where it doesn't recognize the component as a function. So I would rename user.js > anything.js then back to user.js and see if it finds the import.
this did not resolve my problem, i renamed everything and changed it back
I am unsure if this would cause an import error like this, but you called the app.listen twice in your app.js At the top of the file, the app.listen contains the PORT variable, defined near the bottom. That could cause a reference error. Perhaps comment out the app.listen near the top of the file and see if it changes/resolves the error.
Hi lewis, this still gives me the same error. I dont think it got something to do about that
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.